模版方法模式(行为型)
2016-10-19 21:13
393 查看
模板方法
定义一个操作中的算法的骨架,将一些步骤延迟到子类中。
TemplateMethod使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。适用性
1.一次性实现一个算法的不变的部分,并将可变的留给子类来实现。
2.各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复。
首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。
最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。
3.控制子类扩展。
结构类图
head_first类图
系统结构图
------------------------------
具体子类
--------------------------------
public class CoffeeWithHook extends CaffeineBeverage { @Override public void addCondiments() { // TODO Auto-generated method stub System.out.println("add the Coffee"); } @Override public void brew() { // TODO Auto-generated method stub System.out.println("add the Mike"); } public boolean hook(){ System.out.println("do you want to implement parent method"); Scanner in=new Scanner(System.in); if(in.next().equals("y")){ return true; }else{ return false; } } } public class Tea extends CaffeineBeverage{ @Override public void addCondiments() { // TODO Auto-generated method stub System.out.println("add the Tea"); } @Override public void brew() { // TODO Auto-generated method stub System.out.println("adding lemon"); } }
---------------------------------
模版
------------------------------
public abstract class CaffeineBeverage {public final void prepareRecipe() {boidWater();brew();pourInCup();if (hook()) {addCondiments();}}public abstract void addCondiments();public abstract void brew();public void pourInCup() {// TODO Auto-generated method stubSystem.out.println("pour into cup");}public void boidWater() {// TODO Auto-generated method stubSystem.out.println("pour the water");}//define a hook methodpublic boolean hook() {return true;}}[/code]
---------------------------------
测试类
---------------------------------
public class TestC {public static void main(String[] args) {// TODO Auto-generated method stubCaffeineBeverage coffeeWithHook=new CoffeeWithHook();coffeeWithHook.prepareRecipe();System.out.println("---------------------");CaffeineBeverage tea=new Tea();tea.prepareRecipe();}}[/code]
------------------------------------
结果
----------------------------------
pour the wateradd the Mikepour into cupdo you want to implement parent methodyadd the Coffee---------------------pour the wateradding lemonpour into cupadd the Tea
---------------------------------------------------
具体应用场景
相关文章推荐
- 二十五.行为型设计模式——Template Method Pattern(模版方法模式)
- 行为型模式9:模版方法模式(Template Method)
- (第Ⅳ部分 行为型模式篇) 第15章 模版方法模式(Template Method)
- 设计模式(十五)—模版方法(行为型)
- 设计模式->行为型模式->模版方法模式
- 设计模式之行为型模式―― 3.6 模版方法模式
- (第Ⅳ部分 行为型模式篇) 第15章 模版方法模式(Template Method)
- 行为型模式之模版方法模式
- 23种设计模式(13)_行为型_模版方法模式(Template Method)
- 设计模式-模版方法(行为型)
- 行为型:设计模式之模版方法模式(十七)
- 设计模式(三)模版方法(行为型)
- 模版方法--行为型模式之二:类的关系
- (第Ⅳ部分 行为型模式篇) 第15章 模版方法模式(Template Method)
- 设计模式学习总结11 - 行为型6 - TemplateMethod模版方法模式
- Java设计模式_(行为型)_模版方法模式
- .NET设计模式(16):模版方法(Template Method)
- .NET设计模式-模版方法(Template Method)
- C#面向对象设计模式纵横谈 学习笔记14 Template Method模板方法(行为型模式)
- Java与模式 模版方法模式 Template Method