Do we have pattern, which is opposite to Template Method?
I mean, in base class we define parts of algorithm and abstract method which implements algorithm. Then in derived class, in that abstract method, we can mix those parts as we want.
Do we have pattern, which is opposite to Template Method?
I mean, in base class we define parts of algorithm and abstract method which implements algorithm. Then in derived class, in that abstract method, we can mix those parts as we want.
What you describe is basic polymorphism:
class Receipee {
public:
void get_eggs(int n) { cout << "I take "<<n<<" eggs" <<endl; }
void get_chocolate (int weight) { cout << "I take "<<weight<<" g chocolate" <<endl; }
void get_milk(int l) { cout << "I take "<<l<<" cl of milk" <<endl; }
void mix_it(int force) { cout << "I mix everything force "<<force<<endl; }
virtual void prepare() = 0;
};
class Receipee1 : public Receipee {
public:
void prepare() override {
get_milk(100);
get_eggs(2);
cout << "I do some mystery trick"<<endl;
mix_it(3);
cout << "Et voilà !" <<endl;
}
};
No need for pattern for that ;-)
get_eggs
etc needs to be public. protected
might be enough (except, one would like to unit-test those methods directly).
Dec 5, 2018 at 19:34
It's the strategy pattern. In the strategy pattern, the main method of the base (which implements the algorithm) is abstract — the algorithm is meant to be implemented by subs. Whereas in template method pattern, this main method is concrete/dictated while only piece parts are abstract.
These patterns are both thoughtful application of class hierarchy and overriding. However, to be sure, many variations are possible to suit various needs. So, we can have abstract and concrete methods defined in the base to be used as needed (as helpers and/or as mains). When the main a algorithm is concrete in the base we call it template, and when abstract we call it strategy. Sometimes we mix both, meaning a concrete yet override-able main in the base.
From my understanding, the Template Method is a KIND of Strategy Pattern. The difference is they both provide solutions to a "plug and play" algorithm problem.
Although there is a general rule of thumb in that we should favor Composition over Inheritance. People much smarter than myself have pointed out that, over the long term inheritance can provide more challenges than solutions. So rather than, templating your code, you should opt to inject the algorithm (or strategies) as you need them. In short, you should use the strategy pattern if you're looking to keep things decoupled and flexible and inject the behaviors according to your Use Case.