Template Method (TemplateMethod) mode

  The method of preparing the template model is an abstract class, the specific part of the logic in the form of methods and constructors, and abstract method declarations to force the remaining subclasses implement logic. Different subclasses of abstract methods may be implemented in different ways, so that different implementations of the remaining logic portion. This is also the intention of the template method pattern.

  Template Method pattern is the basic technology reuse of code-based inheritance.

 1. Structure

   Static structure template method pattern is as follows:

Role involves the following:

Abstract template role (AbstractClass): its main responsibilities are as follows

(1) defines one or more abstract operation, so that subclasses implement. These operations are called the basic operations, which are composed of a top-level logical step.

(2) define and implement a template method. This method is generally a specific template method, which gives a top-level logical skeleton, which consists of a step in the corresponding abstract logical operations, deferred to subclasses implement. Top logic may also be some specific method calls.

Specific template (ConcretrClass) role: its responsibilities as follows

One or more abstract methods (1) to achieve the parent class definition, which is composed of a top-level logical step.

(2) Each character abstract template can have any number of specific characters corresponding template, and the template for each particular character can be given different implementations of these abstract methods, so that the top achieve different logic.

 

code show as below:

Package cn.qlq.teplate; 

public  abstract  class the AbstractClass { 

    public  void templateMethod () {
         // before treatment 

        doOperation1 (); 

        doOperation2 (); 

        doOperation3 (); 

        // workup 
    } 

    void doOperation1 () { 
        System.out.println ( "doOperation1 default implementation" ); 
    } 

    abstract  void doOperation2 (); 

    abstract  void doOperation3 (); 

}

   The basic method doOperation1 (), doOperation2 (), doOperation3 () and the like are composed of the top step logic. The logic is represented by the top templateMethod method. DoOperation1 abstract class provides default implementations, doOperation2 and doOperation3 to subclasses to achieve.

 

package cn.qlq.teplate;

public class ConcreteClass1 extends AbstractClass {
    
    @Override
    void doOperation2() {
        System.out.println("ConcreteClass1 doOperation2");
    }

    @Override
    void doOperation3() {
        System.out.println("ConcreteClass1 doOperation3");
    }

}
package cn.qlq.teplate;

public class ConcreteClass2 extends AbstractClass {

    @Override
    void doOperation1() {
        System.out.println("ConcreteClass2 doOperation1");
    }

    @Override
    void doOperation2() {
        System.out.println("ConcreteClass2 doOperation2");
    }

    @Override
    void doOperation3() {
        System.out.println("ConcreteClass2 doOperation3");
    }

}

 

Client code:

package cn.qlq.teplate;

public class Client {

    public static void main(String[] args) {
        AbstractClass abstractClass = new ConcreteClass2();
        abstractClass.templateMethod();
    }

}

result:

ConcreteClass2 doOperation1
ConcreteClass2 doOperation2
ConcreteClass2 doOperation3

 

2. Examples

  Examples of a bank interest. It requires two assumptions bank deposit accounts, money market accounts (MoneyMarket) and regular (Certificate of Deposite) deposit account. Overall behavior of the system is to calculate the interest, which also determines the template as a top logical method should be the interest calculation. Interest calculation involves two steps: First, determine the type of account, the second is to determine the percentage of interest.

Structure is as follows:

  Implementation of Template Method pattern from top to bottom, that is to say the need to give top logic, and gives a logical step in the concrete.

 

code show as below:

package cn.qlq.template;

public abstract class Account {

    protected String accountNumber;

    public Account(String accountNumber) {
        super();
        this.accountNumber = accountNumber;
    }

    public final double calculateInterest() {
        double interestRate = doCalculateInterestRate();
        String accountType = doCalculateAccountType();
        double amount = doCalculateAmount(accountType, accountNumber);

        return amount * interestRate;
    }

    abstract double doCalculateAmount(String accountType, String accountNumber2);

    abstract String doCalculateAccountType();

    abstract double doCalculateInterestRate();

}

 

package cn.qlq.template;

public class CDAccount extends Account {

    public CDAccount(String accountNumber) {
        super(accountNumber);
    }

    @Override
    double doCalculateAmount(String accountType, String accountNumber2) {
        // 模拟从数据库查出数据
        return 50D;
    }

    @Override
    String doCalculateAccountType() {
        return "CDAccount";
    }

    @Override
    double doCalculateInterestRate() {
        return 0.048D;
    }

}
package cn.qlq.template;

public class MoneyMarket extends Account {

    public MoneyMarket(String accountNumber) {
        super(accountNumber);
    }

    @Override
    double doCalculateAmount(String accountType, String accountNumber2) {
        // 模拟从数据库查出数据
        return 50D;
    }

    @Override
    String doCalculateAccountType() {
        return "Money Market";
    }

    @Override
    double doCalculateInterestRate() {
        return 0.045D;
    }

}

 

Client code:

package cn.qlq.template;

public class Client {
    public static void main(String[] args) {
        Account account = new CDAccount("123");
        double calculateInterest = account.calculateInterest();
        System.out.println(calculateInterest);

        Account moneyMarket = new MoneyMarket("123");
        double moneyMarketInterest = moneyMarket.calculateInterest();
        System.out.println(moneyMarketInterest);
    }
}

 

3. Summary

1. inherited as a tool multiplexed

(1) First, Java beginners do not know what is inherited, or that inheritance is profound tool. Designed most of its functions are performed by delegation.

(2) slowly discovered inheritance is not difficult, and can make an initial understanding of the subclass inherits all of a sudden get the behavior of the parent class. So try to inherit the main tool functions as multiplexing, and the original use of the local delegation should instead use inheritance, this time caused by inherited abuse.

 (3) design is also promoting the use of delegated relationship instead of inheritance. Such as status mode, strategy pattern, decorative pattern, bridge mode.

(4) In fact encapsulation, inheritance, and polymorphism and abstraction called object-oriented features. So it should be a reasonable use of inheritance.

 

2. The template method pattern Java language

 HttpServlet technology on the use of a template method pattern. HttpServlet provides a service () method, or a method call several methods do 7, to complete the processing of client calls.

 

3. Template Method Methods

  Methods template method can be divided into two categories: basic template approach and method.

Template Method:

  The method is generally in an abstract class, the basic method of combining together to form a general definition of a method or behavior. This method is generally defined in an abstract class and not inherited completely be modified by subclasses.

  An abstract class can have any number of template methods, not limited to one. Each template method are any number of specific methods can be called.

basic method:

  The basic method is divided into three types: the abstract methods, specific methods and hook method

(1) abstract methods: by a concrete subclass of abstract class declaration implemented

(2) specific methods: the abstract and implemented by a class declaration, the sub-class does not implement or substitutions. Some specific methods can play the role of the factory method, this method is also called specific factory methods.

 (3) hook method: a hook method and implemented by the abstract class declaration, but subclasses will be expanded. Abstract class typically implement a given blank is achieved, as a method to achieve the default (also seen in the default adapter mode).

 

Note naming rules:

  Hook method name should begin to do, which is familiar with design patterns Java programmers standard practice. In HttpServlet also follow this rule.

 

Guess you like

Origin www.cnblogs.com/qlqwjy/p/11245923.html