模板模式及应用

定义

模板模式在 GoF 的《设计模式》一书中,是这么定义的:

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

大体意思就是:定义好框架,某些具体的实现由子类完成。

好处 : 框架复用,具体实现可以扩展

应用

如Java Servlet、JUnit TestCase、Java InputStream、Java AbstractList 等。

1、AbstractList
  public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }
2、JUnit TestCase

Junit在整体流程中提供的扩展点,setUp()、tearDown() 等。

posted @ 2020-05-21 16:34  walterlee  阅读(110)  评论(0编辑  收藏  举报