您的位置:首页 > 其它

模版方法模式(行为型)

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
---------------------------------------------------
具体应用场景
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: