首页 > 其他 > 详细

设计模式(模板方法)

时间:2015-06-15 12:31:42      阅读:72      评论:0      收藏:0      [点我收藏+]

模板方法是通过抽象类定义各一个基础模板,这个模板中有已经实现的,也有要求强制子类实现的。

通过这个模板的定义来实现有约束的业务继承。代码如下:

  • Template
public abstract class Template {
    public void templateMethod(){
        baseMethod();
        subMehtod();
    }
    
    public void baseMethod(){
        System.out.println("baseMethod");
    }
    
    public abstract void subMehtod();
}
  • ConcreteOne&ConcreteTwo
public class ConcreteOne extends Template {

    @Override
    public void subMehtod() {
        System.out.println("ConcreteOne");
    }
}

public class ConcreteTwo extends Template {

    @Override
    public void subMehtod() {
        System.out.println("ConcreteTwo");
    }
}
  • App 测试类
public class App {

    public static void main(String[] args) {
        Template temp = new ConcreteOne();
        temp.templateMethod();
        temp = new ConcreteTwo();
        temp.templateMethod();
    }
}

 

设计模式(模板方法)

原文:http://www.cnblogs.com/Fredric-2013/p/4576576.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!