head first 设计模式笔记8-模板方法模式

  模板设计模式:就是定义一个算法的骨架,而将具体的算法延迟到子类中来实现。

  优点:使用模板方法模式,在定义算法骨架的同时,可以很灵活的实现具体的算法,满足用户灵活多变的需求。

  缺点:如果算法骨架有修改的话,则需要修改抽象类。

   策略模式和模板设计模式都封装算法,前者使用组合,后者使用继承。

/**
 * @author oy
 * @date 2019年9月8日 下午8:52:00
 * @version 1.0.0
 */
public abstract class GetTime {
    public static void main(String[] args) {
        GetTImeImpl impl = new GetTImeImpl();
        impl.getTime();
    }
    
    public long getTime() {
        long start = System.currentTimeMillis();
        
        code();
        
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("运行时间为 " + time + "毫秒");
        return time;
    }

    public abstract void code();
}

  GetTImeImpl

public class GetTImeImpl extends GetTime {

    @Override
    public void code() {
        for (int i = 0; i < 100000; i ++) {
            System.out.println(i);
        }
    }

}
原文地址:https://www.cnblogs.com/xy-ouyang/p/11488453.html