标签:style blog http io ar java sp 2014 c
定义:定义一个操作的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
结构图:
示例代码:
public abstract class AbstractClass { public abstract void primitiveOperation1(); public abstract void primitiveOperation2(); public void templateMethod() { primitiveOperation1(); primitiveOperation2(); System.out.println(); } } public class ConcreteClassA extends AbstractClass { @Override public void primitiveOperation1() { // TODO Auto-generated method stub System.out.println("具体类A方法1实现"); } @Override public void primitiveOperation2() { // TODO Auto-generated method stub System.out.println("具体类A方法2实现"); } } public class ConcreteClassB extends AbstractClass { @Override public void primitiveOperation1() { // TODO Auto-generated method stub System.out.println("具体类B方法1"); } @Override public void primitiveOperation2() { // TODO Auto-generated method stub System.out.println("具体类B方法2"); } }客户端代码:
public class Client { public static void main(String[] args) { AbstractClass abstractClass = null; abstractClass = new ConcreteClassA(); abstractClass.templateMethod(); abstractClass = new ConcreteClassB(); abstractClass.templateMethod(); } }
运行结果:
具体类A方法1实现
具体类A方法2实现
具体类B方法1
具体类B方法2
标签:style blog http io ar java sp 2014 c
原文地址:http://blog.csdn.net/tiandesheng111/article/details/39777969