Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The main difference between the two is when the concrete algorithm is chosen.</p> <p>With the <strong>Template method pattern</strong> this happens at <em>compile-time</em> by <em>subclassing</em> the template. Each subclass provides a different concrete algorithm by implementing the template's abstract methods. When a client invokes methods of the template's external interface the template calls its abstract methods (its internal interface) as required to invoke the algorithm.</p> <pre><code>class ConcreteAlgorithm : AbstractTemplate { void DoAlgorithm(int datum) {...} } class AbstractTemplate { void run(int datum) { DoAlgorithm(datum); } virtual void DoAlgorithm() = 0; // abstract } </code></pre> <p>In contrast, the <strong>Strategy pattern</strong> allows an algorithm to be chosen at <em>runtime</em> by <em>containment</em>. The concrete algorithms are implemented by separate classes or functions which are passed to the strategy as a parameter to its constructor or to a setter method. Which algorithm is chosen for this parameter can vary dynamically based on the program's state or inputs.</p> <pre><code>class ConcreteAlgorithm : IAlgorithm { void DoAlgorithm(int datum) {...} } class Strategy { Strategy(IAlgorithm algo) {...} void run(int datum) { this-&gt;algo.DoAlgorithm(datum); } } </code></pre> <h2>In summary:</h2> <ul> <li>Template method pattern: <strong>compile-time</strong> algorithm selection by <strong>subclassing</strong></li> <li>Strategy pattern: <strong>run-time algorithm</strong> selection by <strong>containment</strong></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload