definition
就是定义算法骨架的方法 具体的操作:在模板中直接实现某些步骤的方法,通常这些步骤的实现算法是固定的,而且是不怎么变化的,因此就可以当作公共功能实现在模板里面。
其实写设计模式的系列笔记就是一种模板方法,每篇文章的流程(目录)都是一样的,我实现了每个部分的具体细节。
template
Template method is relatively simple, first heard the concept, I found myself one kind is called template method originally used.
Template Method TemplateMethod is to achieve in an abstract class, and this particular method which uses a number of specific processes such as PrimitiveOperation1 / PrimitiveOperation2, as long as the subclass inherits the abstract template and implement specific processes, the ability to be able to provide external template method.
Examples
abstract class Shoping {
// 模板方法,由父类实现,可以定义为final
public final void buyGood() {
login();
order();
pay();
}
abstract void login();
abstract void order();
abstract void pay();
}
JingdongBuy extends Shoping {
public void login() {
Log.d("登录京东账号");
}
public void order() {
Log.d("生成京东订单");
}
public void pay() {
Log.d("使用京东白条支付");
}
}
TaobaoBuy extends Shoping {
public void login() {
Log.d("登录淘宝账号");
}
public void order() {
Log.d("生成淘宝订单");
}
public void pay() {
Log.d("使用支付宝支付");
}
}
advantage
Template based approach to abstract common ground between different operating dissected differences.
Seek common ground: the common ground achieved in an abstract class, different concrete realization of various subclasses reserved.
- Reduce duplication of code, send will follow the expansion and maintenance
- In line with the principle of opening and closing, subclasses can extend the functionality
Shortcoming
- Increase the abstract class
- Read the code more difficult (need to subclass looking to achieve)
Note: Abstract excessive post-expansion may cause trouble, try to ensure that the process will not change after template