Java
Usage examples: The Template Method pattern is quite common in Java frameworks. Developers often use it to provide framework users with a simple means of extending standard functionality using inheritance.
Here are some examples of Template Methods in core Java libraries:
All non-abstract methods of
java.io.InputStream,java.io.OutputStream,java.io.Readerandjava.io.Writer.All non-abstract methods of
java.util.AbstractList,java.util.AbstractSetandjava.util.AbstractMap.In
javax.servlet.http.HttpServletclass, all thedoXXX()methods send the HTTP 405 “Method Not Allowed” error by default. However, you can override any of those methods to send a different response.
Identification: Template Method can be recognized if you see a method in base class that calls a bunch of other methods that are either abstract or empty.
Overriding standard steps of an algorithm
In this example, the Template Method pattern defines an algorithm of working with a social network. Subclasses that match a particular social network, implement these steps according to the API provided by the social network.
networks
networks/Network.java: Base social network class
package refactoring_guru.template_method.example.networks;
/**
* Base class of social network.
*/
public abstract class Network {
String userName;
String password;
Network() {}
/**
* Publish the data to whatever network.
*/
public boolean post(String message) {
// Authenticate before posting. Every network uses a different
// authentication method.
if (logIn(this.userName, this.password)) {
// Send the post data.
boolean result = sendData(message.getBytes());
logOut();
return result;
}
return false;
}
abstract boolean logIn(String userName, String password);
abstract boolean sendData(byte[] data);
abstract void logOut();
}networks/Facebook.java: Concrete social network
networks/Twitter.java: One more social network
Demo.java: Client code
OutputDemo.txt: Execution result
Last updated