Can someone please explain to me what is the difference between the template method pattern and the strategy pattern is?
As far as I can tell they are 99% the same -
The Template pattern is similar to the Strategy pattern. These two patterns differ in scope and in methodology.
Strategy is used to allow callers to vary an entire algorithm, like how to calculate different types of tax, while Template Method is used to vary steps in an algorithm. Because of this, Strategy is more coarsely grained. The Template allows finer-grained controls in the sequent of operations, and yet allows the implementations of these details to vary.
The other main difference is that Strategy uses delegation while Template Method uses inheritance. In Strategy, the algorithm is delegated to the another xxxStrategy class that the subject will have a reference to, but with Template you subclass the base and override methods to make changes.
from http://cyruscrypt.blogspot.com/2005/07/template-vs-strategy-patterns.html
You probably mean template method pattern. You are right, they serve very similar needs. I would say it is better to use template method in cases when you have a "template" algorithm having defined steps where subclasses override these steps to change some details. In case of strategy, you need to create an interface, and instead of inheritance you are using delegation. I would say it is a bit more powerful pattern and maybe better in accordance to DIP - dependency inversion principles. It is more powerful because you clearly define a new abstraction of strategy - a way of doing something, which does not apply to template method. So, if this abstraction makes sense - use it. However, using template method may give you simpler designs in simple cases, which is also important. Consider which words fit better: do you have a template algorithm? Or is the key thing here that you have an abstraction of strategy - new way of doing something
Example of a template method:
Application.main()
{
Init();
Run();
Done();
}
Here you inherit from application and substitute what exactly will be done on init, run and done.
Example of a strategy:
array.sort (IComparer<T> comparer)
Here, when writing a comparer, you do not inherit from an array. Array delegates the comparison algorithm to a comparer.
Both are very similar, and both are consumed by the client code in similar ways. Unlike what the most popular answer above says, both allow algorithm selection at run-time.
The difference between the two is that while the strategy pattern allows different implementations to use completely different ways of the achieving the desired outcome, the template method pattern specifies an overarching algorithm (the "template" method) which is be used to achieve the result -- the only choice left to the specific implementations (sub-classes) are certain details of the said template method. This is done by having the the template method make call(s) to one or more abstract methods which are overridden (i.e. implemented) by the sub-classes, unlike the template method which itself is not abstract and not overridden by the sub-classes.
The client code makes a call to the template method using a reference/pointer of the abstract class type pointing to an instance of one of the concrete sub classes which can be determined at run time just like while using the Strategy Pattern.
In strategy pattern subclasses are running the show and they control the algorithm. Here code is duplicated across the subclasses. The knowledge of the algorithm and how to implement it is distributed over many classes.
In template pattern, base class has algorithm. It maximizes the reuse among the subclasses. Since algorithm lies in one place, base class protects it.
Template method is about letting subclasses redefine certain steps of the algorithm, without changing the main structure and steps of the algorithm, defined in the base class. Template pattern usually uses inheritance, so a generic implementation of algorithms can be provided in the base class, which the subclass might choose to override if needed.
public abstract class RobotTemplate {
/* This method can be overridden by a subclass if required */
public void start() {
System.out.println("Starting....");
}
/* This method can be overridden by a subclass if required */
public void getParts() {
System.out.println("Getting parts....");
}
/* This method can be overridden by a subclass if required */
public void assemble() {
System.out.println("Assembling....");
}
/* This method can be overridden by a subclass if required */
public void test() {
System.out.println("Testing....");
}
/* This method can be overridden by a subclass if required */
public void stop() {
System.out.println("Stopping....");
}
/*
* Template algorithm method made up of multiple steps, whose structure and
* order of steps will not be changed by subclasses.
*/
public final void go() {
start();
getParts();
assemble();
test();
stop();
}
}
/* Concrete subclass overrides template step methods as required for its use */
public class CookieRobot extends RobotTemplate {
private String name;
public CookieRobot(String n) {
name = n;
}
@Override
public void getParts() {
System.out.println("Getting a flour and sugar....");
}
@Override
public void assemble() {
System.out.println("Baking a cookie....");
}
@Override
public void test() {
System.out.println("Crunching a cookie....");
}
public String getName() {
return name;
}
}
Note in the above code, the go() algorithm steps will always be the same, but the subclasses might define a different recipe for performing a particular step.
Strategy pattern is about letting client selects concrete algorithms implementation at runtime. All algorithms are isolated and independent, but implement a common interface, and there is no notion of defining particular steps within the algorithm.
/**
* This Strategy interface is implemented by all concrete objects representing an
* algorithm(strategy), which lets us define a family of algorithms.
*/
public interface Logging {
void write(String message);
}
/**
* Concrete strategy class representing a particular algorithm.
*/
public class ConsoleLogging implements Logging {
@Override
public void write(String message) {
System.out.println(message);
}
}
/**
* Concrete strategy class representing a particular algorithm.
*/
public class FileLogging implements Logging {
private final File toWrite;
public FileLogging(final File toWrite) {
this.toWrite = toWrite;
}
@Override
public void write(String message) {
try {
final FileWriter fos = new FileWriter(toWrite);
fos.write(message);
fos.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
For full source code, check out my github repository.
Template Method:
Template_method structure:
Strategy:
Strategy structure:
Have a look at Template method and Strategy articles for better understanding.
Related posts:
Template design pattern in JDK, could not find a method defining set of methods to be executed in order
Real World Example of the Strategy Pattern