23 design patterns of the template method (Template Pattern)

The algorithm defines a skeleton of the operation, some steps to subclasses delay. Method template so that subclasses can not change the structure of the algorithm to a certain step of the algorithm redefine

  • AbstractClass: abstract class. Algorithm is used to define the skeleton and primitive operations, which in this class, the algorithm may also provide common implementation
  • ConcreteClass: implementation class. Some steps of the algorithm used to implement the backbone, associated with completion of a particular subclass

Advantages:  1, the same part of the package, a variable extension portion. 2, extracts the common code, easy to maintain. 3, the behavior control by the parent class, subclass achieved.

Disadvantages: each requires a different implementation to implement a subclass, resulting in an increase of the number of classes, making the system more bulky.

Be used:  1, a number of methods common subclass, and the same logic. 2, important, complex methods can be considered as a template method.

Application examples:  1, when in a house built, foundations, wiring, water pipes are the same, only in the latter part of the building only difference closet plus plus fences. 2, spring in support for Hibernate, and some have been given good way to encapsulate such as opening a transaction to acquire Session, Session is closed and so on, the programmer does not repeat those already write good code norms, direct throw an entity can be saved

1  / * *
 2  * define a template method, primitive operations such as abstract classes
 . 3   * / 
. 4  public  abstract  class the AbstractClass {
 . 5      / * *
 . 6       * primitive operations 1, a so-called primitive operation of the abstract operation, must be by the sub class provides an implementation
 . 7       * / 
. 8      public  abstract  void doPrimitiveOperation1 ();
 . 9      / * *
 10       * primitive operations 2
 . 11       * / 
12 is      public  abstract  void doPrimitiveOperation2 ();
 13 is      / * *
 14       * template method, algorithm definition skeleton
 15       * / 
16     public Final void templateMethod () {
 . 17          doPrimitiveOperation1 ();
 18 is          doPrimitiveOperation2 ();
 . 19      }
 20 is  }
 21 is  
22 is  / * *
 23 is  * specific implementation classes that implement primitive operations
 24   * / 
25  public  class ConcreteClass the extends the AbstractClass {
 26 is      public  void doPrimitiveOperation1 () { 
 27          // specific implementation 
28      }
 29      public  void doPrimitiveOperation2 () { 
 30          // specific implementation 
31     }
32 }
View Code

 

Guess you like

Origin www.cnblogs.com/Dewumu/p/11490393.html