设计模式(模板方法)

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

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

  • 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();
    }
}

 

posted @ 2015-06-15 10:53  Fredric_2013  阅读(149)  评论(0编辑  收藏  举报