最简单的设计模式,主要用到的Java的继承
先声明一个抽象类做为模版
package TemplateMethod; /** * Created by Zz on 2017/5/3 0003. */ public abstract class People { public void doSomething() { beforeMethod(); method(); afterMethod(); } /** * 声明为protect final 是为了不让子类去覆写,同时又允许子类访问 */ protected final void beforeMethod() { System.out.println("beforeMethod"); }; protected abstract void method(); protected final void afterMethod() { System.out.println("afterMethod"); }; }以下为模版类的实现
package TemplateMethod; /** * Created by Zz on 2017/5/3 0003. */ public class Men extends People { @Override public void method() { System.out.println("men method"); } } package TemplateMethod; /** * Created by Zz on 2017/5/3 0003. */ public class Women extends People { @Override public void method() { System.out.println("women method"); } }测试运行结果
package TemplateMethod; /** * Created by Zz on 2017/5/3 0003. */ public class Test { public static void main(String[] args) { People people = new Men(); people.doSomething(); } }输出结果:
beforeMethod men method afterMethod