目的:
在一个操作中定义算法的骨架,将某些步骤推迟到子类。模板方法允许子类重新定义算法的某些步骤,而无需更改算法的结构。
程序示例:
偷东西的一般步骤是相同的。 首先,选择目标,然后以某种方式使其迷惑,最后,你偷走了该物品。然而这些步骤有很多实现方式。
1.定义模板方法
@Slf4j
public abstract class StealingMethod{
protected abstract String pickTarget();
protected abstract void confuseTarget(String target);
protected abstract void stealTheItem(String target);
/**
* 定义方法的顺序
*/
public void steal(){
String target = pickTarget();
log.info("The target has been chosen as {}.", target);
confuseTarget(target);
stealTheItem(target);
}
}
2.定义不同的方法子类实现
@Slf4j
public class SubtleMethod extends StealingMethod{
@Override
protected String pickTarget() {
return "shop keeper";
}
@Override
protected void confuseTarget(String target) {
log.info("Approach the {} with tears running and hug him!", target);
}
@Override
protected void stealTheItem(String target) {
log.info("While in close contact grab the {}'s wallet.", target);
}
}
@Slf4j
public class HitAndRunMethod extends StealingMethod{
@Override
protected String pickTarget() {
return "old goblin woman";
}
@Override
protected void confuseTarget(String target) {
log.info("Approach the {} from behind.", target);
}
@Override
protected void stealTheItem(String target) {
log.info("Grab the handbag and run away fast!");
}
}
3.定义使用者
public class HalflingThief{
private StealingMethod method;
public HalflingThief(StealingMethod method) {
this.method = method;
}
public void steal(){
method.steal();
}
public void change(StealingMethod method){
this.method=method;
}
}
4.测试输出
HalflingThief thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.change(new SubtleMethod());
thief.steal();
/*
The target has been chosen as old goblin woman.
Approach the old goblin woman from behind.
Grab the handbag and run away fast!
The target has been chosen as shop keeper.
Approach the shop keeper with tears running and hug him!
While in close contact grab the shop keeper's wallet.
*/
类图: