Design Pattern_Template Pattern

Template pattern is a relatively simple design pattern. It extracts public methods from abstract classes and implements them by subclasses. Just like a template. Each inherited one must implement the methods announced in it. Everyone will say, isn’t this the baseDao that was written when working on the project? That's right. This is the application.

There will be a method to pay attention to. It's the use of hooks. It means that there is an abstract method in the public class, but this method does not need to be called by every object. It may not be called, for example, in a car model, one needs to implement the horn function, but one does not need to be used; in such a scenario, the hook mode can be used.


Basic class diagram.



Code.

public abstract class CarT {
	protected boolean hook = true;
	
	protected abstract void startCar() ;
	protected abstract void stopCar() ;
	
	final public void carRun(){
		this.startCar();
		System.out.println("汽车运行中");
		if(this.hook){
			this.isWhistled();
		}
		this.stopCar();
	}
	
	final public void isWhistled(){
		System.out.println("汽车鸣笛");
	}
	
	public void setHook(boolean _flag){
		this.hook = _flag;
	}
}


public class CarA extends CarT {
	public void startCar(){
		System.out.println("汽车A启动声音是嘟嘟~");
	}

	@Override
	public void stopCar() {
		System.out.println("汽车A停止声音是滴滴~");
	}
}	
public class CarB extends CarT {

	@Override
	protected void startCar() {
		System.out.println("汽车B启动的声音是咚咚~");
	}

	@Override
	protected void stopCar() {
		System.out.println("汽车B启动的声音是叮叮~");
	}

}

public class client {
	public static void main(String args[]){
		CarT carA = new CarA();
		carA.setHook(false);
		carA.carRun();
		System.out.println("======");
		CarT carB = new CarB();
		carB.carRun();
	}
	
}

This is a relatively simple design pattern. Everyone should have seen it.

Guess you like

Origin blog.csdn.net/my_God_sky/article/details/52621109