Head First Design Patterns - Template Method Pattern

The Template Method Pattern defines the skeleton of algorithm in a method, define some steps to 

subclasses. Template Method lets subclass redefine certain steps of an algorithm without changing

the algorithm's structrue.

Class diagram:

abstract class AbstractClass{

  final void templateMethod(){

    primitiveOperation1();

    primitiveOperation2();

    concreteOpration();

  }

  abstract void primitiveOperation1();

  abstract void primitiveOperation2();

  void concreteOperation(){

    // implementation here

  }

  void hook(){}

}

A hook is a method that is declared in the abstract class, but only given an empty or default implementation,use hooks

when that part of the algorithm is optional, with hooks, a subclass may choose to implement that hook, but it doesn't have to.

The Hollywood Priciple:

  • Don't call us, we'll call you

the Hollywood principle gives us a way to prevent "dependency rot". Dependency rot happens when you have high-level 

components depending on low-level components.

The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.

posted @ 2012-04-27 21:19  qiangzhu  阅读(470)  评论(0编辑  收藏  举报