设计模式之模板方法
来源:互联网 发布:java unix时间戳 编辑:程序博客网 时间:2024/05/17 23:58
跟策略方法类似,就是换方法
public class App { public static void main(String[] args) { HalflingThief thief=new HalflingThief(new HitAndRunMethod()); thief.steal(); thief.changeMethod(new SubtleMethod()); thief.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; }}
public class HitAndRunMethod extends StealingMethod{ @Override protected String pickTarget() { return "old goblin woman"; } @Override protected void confuseTarget(String target) { System.out.println("Approch the "+target+" from behind"); } @Override protected void stealTheItem(String target) { System.out.println("Grab the handbag and run away fast"); }}
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(); System.out.println("The target has been chosen as "+target); confuseTarget(target); stealTheItem(target); }}
public class SubtleMethod extends StealingMethod { @Override protected String pickTarget() { return "shop keeper"; } @Override protected void confuseTarget(String target) { System.out.println("Approcch the "+target+" with tears running and hug him!"); } @Override protected void stealTheItem(String target) { System.out.println("While in close contact grab the "+target+"'s wallet"); }}
当替换整个方法时,就是换了个模板
阅读全文
0 0
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法
- 设计模式之模板方法模式模板方法模式
- Java设计模式之模板方法模式
- Express、Socket.io开发一个简易的聊天系统
- Bootstrap中的下拉菜单组件
- GitHub上README.md教程
- 用MATLAB实现FR共轭梯度法求解实例
- linux压缩命令总结
- 设计模式之模板方法
- 递归 与 尾递归 详解
- 提高代码阅读能力的7种方法
- tensorflow中模型的保存和恢复
- (二)Java设计模式之简单工厂模式
- LinkedHashMap和HashMap的比较使用
- 线索二叉树及相关(之后)的一些考点
- 查看CentOS系统的shell脚本语言支持情况
- 手把手教你将Android项目开源到JCenter