设计模式(二十二)----- 模板方法(TemplateMethod)----(JAVA版)

模板模式

   定义一个操作中的算法的骨架,将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可以重定义该算法的某些特定步骤!

适用性

1.一次性实现算法中的不变部分,并且将可变的行为留给子类来实现

2.各子类中公共的行为应被提取出来并且集中到一个公共父类中以避免代码重复。首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。最后,用一个调用这些新的操作的模板方法来替换这些不同的代码

3.控制子类扩展

参与者

1.AbstractClass

   定义抽象的原语操作,本例中就是printInfo(),然后在子类中对它们进行重定义,以实现一个算法的各个步骤, 

   定义一个模板方法update(),然后在里面调用上面的那个原语操作:

2.ConcreteClass

  上述抽象类的一个具体实现

一个例子

1.AbstractClass

public abstract class Template {
 public abstract void printInfo();

 public void update() {
  System.out.println("the result is listed:");
  for (int i = 0; i < 10; i++)
   printInfo();
 }
}

2.ConcreteClass

public class ConcreteTemplate extends Template {

 @Override
 public void printInfo() {
  System.out.println("this is the completed of the subclass!!!");
 }
}

Test

public class Test {
 public static void main(String[] args) {
  Template t = new ConcreteTemplate();
  t.update();
 }
}

result

the result is listed:
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!
this is the completed of the subclass!!!


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值