模板方法模式(Template Method Pattern)
阿新 • • 發佈:2019-02-06
模板方法模式是定義一個演算法的骨架,將演算法的實現延遲到子類中。模板方法使得子類可以不改變一個演算法的結構即可重定義演算法的某些特定步驟。
在這個例子中,演算法骨架是StealingMethod,然後定義了兩個演算法的具體實現類:SubtleMethod和HitAndRunMethod。演算法呼叫者為Halfling Thief,呼叫者只關心StealingMethod,而具體的演算法實現由具體的場景來具體指定。
類圖:
程式碼:
/** * * Template Method defines a skeleton for an algorithm. The algorithm subclasses provide * implementation for the blank parts. * <p> * In this example {@link HalflingThief} contains {@link StealingMethod} that can be changed. First * the thief hits with {@link HitAndRunMethod} and then with {@link SubtleMethod}. * */ public class App { /** * Program entry point * * @param args command line args */ public static void main(String[] args) { HalflingThief thief = new HalflingThief(new HitAndRunMethod()); thief.steal(); thief.changeMethod(new SubtleMethod()); thief.steal(); } }
/** * * Halfling thief uses {@link StealingMethod} to steal. * */ public class HalflingThief { private StealingMethod method; public HalflingThief(StealingMethod method) { this.method = method; } public void steal() { method.steal(); } public void changeMethod(StealingMethod method) { this.method = method; } }
/** * * StealingMethod defines skeleton for the algorithm. * */ public abstract class StealingMethod { private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class); protected abstract String pickTarget(); protected abstract void confuseTarget(String target); protected abstract void stealTheItem(String target); /** * Steal */ public void steal() { String target = pickTarget(); LOGGER.info("The target has been chosen as {}.", target); confuseTarget(target); stealTheItem(target); } }
/**
*
* HitAndRunMethod implementation of {@link StealingMethod}.
*
*/
public class HitAndRunMethod extends StealingMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class);
@Override
protected String pickTarget() {
return "old goblin woman";
}
@Override
protected void confuseTarget(String target) {
LOGGER.info("Approach the {} from behind.", target);
}
@Override
protected void stealTheItem(String target) {
LOGGER.info("Grab the handbag and run away fast!");
}
}
/**
*
* SubtleMethod implementation of {@link StealingMethod}.
*
*/
public class SubtleMethod extends StealingMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class);
@Override
protected String pickTarget() {
return "shop keeper";
}
@Override
protected void confuseTarget(String target) {
LOGGER.info("Approach the {} with tears running and hug him!", target);
}
@Override
protected void stealTheItem(String target) {
LOGGER.info("While in close contact grab the {}'s wallet.", target);
}
}