You might see some method chainning usage in JQuery like this:
$('#obj').animate(a).slideUp(b).fadeOut(c);
Actually, this is very simple to implement, all we need to do is to return the object itself as a pointer rather than void type.
class Price {
private:
int v;
public:
Price(int _v) {
v = _v;
}
Price* Raise(int offset) {
v += offset;
return this; // return this object for next chainning method
}
Price* Drop(int offset) {
v -= offset;
return this;// return this object for next chainning method
}
Price* Print() {
cout << v << endl;
return this;// return this object for next chainning method
}
};
So after modification of internal attributes, we return this, which can be used to chain the next method.
Price x(10);
x.Raise(200)->Drop(50)->Print();
The above example usage prints 160. Because we initialize the price to 10 and increment 200 and drop 50. This will make your code much cleaner and is a good OOP (Object Oriented) design principle.
Feature Comments
I prefer chaining using references in cpp. Allows to avoid strange and dangerous pointer operations. And, of course, it is more concise.
class Price {
private:
int v;
public:
Price(int _v) {
v = _v;
}
Price& Raise(int offset) {
v += offset;
return *this; // return this object for next chainning method
}
Price& Drop(int offset) {
v -= offset;
return *this;// return this object for next chainning method
}
Price& Print() {
cout << v << endl;
return *this;// return this object for next chainning method
}
};
This is an example of the builder design pattern.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Greedy Algorithm to Compute the Largest Number
Next Post: Does CloudFlare (Cache Everything) Affect the Adsense?