Detailed template method pattern (with java language source code)

The method of stencil pattern (the Pattern Template) :

The algorithm defines a skeleton of the operation, some steps to subclasses delay. TemplateMethod such subclasses may not change the structure of certain steps of an algorithm of the algorithm to redefine. (Define the skeleton of an algorithm inan operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing thealgorithm's structure.)

Core : process step well defined in the parent class, subclass specific implementation delay to implement.

When used template method pattern : When implementing an algorithm, the overall steps are fixed. However, some parts of the volatile, volatile portions can be abstracted out for subclasses to implement.

Development of common scenarios : very often, each framework, class library has his shadow. such as:

  1. Database access package;
  2. Junit unit testing;
  3. About the servlet doGet / doPost method call;
  4. Hibernate template program;
  5. In spring JDBCTemplate, HibernateTemplate etc.

Case : For example, customers to the bank to conduct business, to the following three processes:

  1. Take a number queue;
  2. Handle specific business (to save money, transfer, financial management, etc.);
  3. Bank staff score;

The method of template patterns, code to achieve the following:

package designpattern.templatemethod;

public abstract class BankTemplateMethod {
	//具体方法
	public void takeNumber(){
		System.out.println("取号排队");
	}
	
	public abstract void transact(); //办理具体的业务	//钩子方法
	
	public void evaluate(){
		System.out.println("反馈评分");
	}
	
	public final void process(){	//模板方法!!!
		this.takeNumber();
		this.transact();
		this.evaluate();
	}
}
package designpattern.templatemethod;

public class Client {
	public static void main(String[] args) {
		BankTemplateMethod btm = new DrawMoney();
		btm.process();
		
		//采用匿名内部类
		BankTemplateMethod btm2 = new BankTemplateMethod() {
			@Override
			public void transact() {
				System.out.println("我要存钱!");
			}
		};
		btm2.process();
		
		BankTemplateMethod btm3 = new BankTemplateMethod() {
			@Override
			public void transact() {
				System.out.println("我要理财!我这里有2000万韩币");
			}
		};
		btm3.process();
	}
}



class DrawMoney extends BankTemplateMethod {
	@Override
	public void transact() {
		System.out.println("我要取款!!!");
	}
}

Execution results as shown below:
Here Insert Picture Description

If you want to know more design patterns, you can visit: Introduction Overview of design patterns and 23 kinds of design patterns

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/91972353