Liar design Mode-Template method mode

Source: Internet
Author: User

In the template method pattern (Templatemethod pattern), an abstract class exposes a way/template that defines the method that executes it. Its subclasses can override the method implementation as needed, but the invocation will be done in the way defined in the abstract class. This type of design pattern belongs to the behavioral pattern.

In the big talk design pattern, geoscience teacher gives the definition is: Template method Mode: Define the skeleton of an algorithm in an operation, and defer some steps to the subclass. The template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm .

One of the frequently used examples is the support for Hibernate in Spirng , which encapsulates some of the already-established methods, such as opening a transaction, getting a session, closing a session, and so on, and we don't have to repeat the code that is already well-regulated. An entity can be saved directly.

The structure diagram of the template method pattern is as follows:

The code examples are as follows:

AbstractClass abstract class is actually an abstract template, which defines and implements a template method. This template method is generally a concrete method, it gives a top-level logical skeleton, and the logical composition step in the corresponding abstract operation, deferred to the subclass implementation; Top-level logic is also possible to invoke some concrete methods.

//abstract class, implemented some template methods  public  class  abstract  abstractclass{//some abstract behavior, put it into subclasses to implement  public  abstract  void      PrimitiveOperation1  (); public  abstract  void  primitiveoperation2     ();    //template method, gives the logical skeleton, and the logical composition is some corresponding abstract operation, they all deferred to the subclass to implement the  public  final void          Templatmethod  () {initialize ();        PrimitiveOperation1 ();    PrimitiveOperation2 (); }}

The Concreteclass class implements one or more abstract methods defined by the parent class. Each abstractclass can have any number of concreteclass corresponding to it, and each concreteclass can give the different implementations of these abstract methods (that is, different implementations of the top-level logical constituent steps), thus making the implementation of the top-level logic varied.

Note the order of the methods in the Concreteclass class and the order of the methods in the template class, and the logical order of implementation is related to the logical sequence defined in the template.

//An implementation class A for an abstract class PublicClass Concreteclassa extends abstractclass{@Override     Public void PrimitiveOperation2() {System. out. println ("Class A concrete implementation method 2"); } @Override Public void Initialize() {System. out. println ("Cocreteclassa Initialized"); }    @Override     Public void PrimitiveOperation1() {System. out. println ("Class A concrete implementation method 1"); }}
//An implementation class B for an abstract class PublicClass CONCRETECLASSB extends abstractclass{@Override     Public void PrimitiveOperation2() {System. out. println ("Class B Concrete Implementation Method 2"); } @Override Public void Initialize() {System. out. println ("Cocreteclassb Initialized"); }    @Override     Public void PrimitiveOperation1() {System. out. println ("Class B Concrete Implementation Method 1"); }}
//测试方法publicstaticvoidmain(String[] args){    AbstractClass ac;    new ConcreteClassA();    ac.TemplatMethod();    new ConcreteClassB();    ac.TemplatMethod();}

Operation Result:

CocreteClassA Initialized类A具体实现方法1类A具体实现方法2CocreteClassB Initialized类B具体实现方法1类B具体实现方法2

Features of the template method pattern:

1, template method mode is to remove the invariant behavior into the superclass, the elimination of duplicate code in the subclass to reflect its advantages;

2, template method mode is to provide a good code reuse platform; sometimes we run into a sequence of steps that need to be executed, and the process is the same at a high level, but some steps can be implemented differently.

3, when the invariant and variable behavior in the method sub-class implementation mix together, the invariant behavior will be repeated in the subclass, we use template method mode to move these behaviors to a single place, so that can help the subclass to get rid of the repetition of the constant behavior of entanglement.

Advantages:

1, the package does not change parts, expand the variable part.

2, the extraction of public code, easy to maintain.

3, the behavior is controlled by the parent class, the subclass implements.

disadvantage : Each of the different implementations need a subclass to implement, resulting in an increase in the number of classes, making the system more large.

Usage scenarios:

1, there are many sub-class common methods, and the same logic.

2, important, complex methods, can be considered as a template method.

Note : To prevent malicious operations, the general template method is added to the final keyword.

Liar design Mode-Template method mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.