模板方法模式

模板方式模式:由父类定义一个算法的骨架,而让具体某些步骤延迟到子类进行实现

模板方法优点:

1.封装不变的部分,扩展变化的部分

2.提取公共部分代码,便于维护

3.行为由父类控制,子类实现

 

标准类图:


模板方法模式
 定义抽象类(抽象类中定义模板方法和基础方法,基础方式由子类进行实现):

public abstract class Hummer {
	
	protected abstract void start();
	
	protected abstract void engineBoom();
	
	protected abstract void alarm();
	
	protected abstract void stop();
	
	public void run(){
		this.engineBoom();
		this.start();
		this.alarm();
		this.stop();
	}
	
}

子类:

public class HummerH1 extends Hummer{

	@Override
	protected void start() {
		System.out.println("hummer h1 start");
	}

	@Override
	protected void engineBoom() {
		System.out.println("hummer h1 engineBoom");
	}

	@Override
	protected void alarm() {
		System.out.println("hummer h1 alarm");
	}

	@Override
	protected void stop() {
		System.out.println("hummer h1 stop");
	}

}

 

public class HummerH1 extends Hummer{

	@Override
	protected void start() {
		System.out.println("hummer h1 start");
	}

	@Override
	protected void engineBoom() {
		System.out.println("hummer h1 engineBoom");
	}

	@Override
	protected void alarm() {
		System.out.println("hummer h1 alarm");
	}

	@Override
	protected void stop() {
		System.out.println("hummer h1 stop");
	}

}

 场景类:

public class Client {
	
	public static void main(String[] args) {
		Hummer hummerh1 = new HummerH1();
		Hummer hummerh2 = new HummerH2();
		hummerh1.run();
		hummerh2.run();
	}
}

 

钩子方法(子类的某个方法返回会影响模板方法的运行结果的方法):

修改抽象类(添加抽象方法isAlarm,交由子类实现,模板方法根据此方法的结果进行主体算法,isAlerm方法为钩子方法):

public abstract class Hummer {
	
	protected abstract void start();
	
	protected abstract void engineBoom();
	
	protected abstract void alarm();
	
	protected abstract void stop();
	
	public void run(){
		this.engineBoom();
		this.start();
		if(isAlarm()){
			this.alarm();
		}
		this.stop();
	}
	
	protected abstract boolean isAlarm();
	
}

 子类:

public class HummerH1 extends Hummer{

	@Override
	protected void start() {
		System.out.println("hummer h1 start");
	}

	@Override
	protected void engineBoom() {
		System.out.println("hummer h1 engineBoom");
	}

	@Override
	protected void alarm() {
		System.out.println("hummer h1 alarm");
	}

	@Override
	protected void stop() {
		System.out.println("hummer h1 stop");
	}

	@Override
	protected boolean isAlarm() {
		return true;
	}

}

 

public class HummerH2 extends Hummer{

	@Override
	protected void start() {
		System.out.println("hummer h2 start");
	}

	@Override
	protected void engineBoom() {
		System.out.println("hummer h2 engineBoom");
	}

	@Override
	protected void alarm() {
		System.out.println("hummer h2 alarm");
	}

	@Override
	protected void stop() {
		System.out.println("hummer h2 stop");
	}

	@Override
	protected boolean isAlarm() {
		return false;
	}

}

 

你可能感兴趣的:(模板方法)