设计模式(4)Java_templateMethod

设计模式(4)Java_templateMethod

1.定义模板类(abstractClass)

package com.lius.patternDesign.templateMethod;
/**
 * templateMethod 模板方法
 * 利用抽象函数与定义一套函数执行主流程,
 * 实现一些变化点延迟实现,交由子类来处理
 * @author lius
 *
 */
public abstract class templateMethod {
	//函数执行控制主流程(模板方法的核心)<模板方法调用子类的变化方法,属于晚调用>
	protected void run() {
		step1();//步骤1
		step2();//步骤2
		step3();//步骤3
		step4();//步骤4
		step5();//步骤5
	}
	
	private void step1() {
		System.out.println(String.format("%s_执行步骤一..",this.getClass().getSuperclass().getSimpleName()));
	}
	protected abstract void step2();//变化点函数只让子类实现,无需提供public,这样是没有意义的
	private void step3() {
		System.out.println(String.format("%s_执行步骤三..", this.getClass().getSuperclass().getSimpleName()));
	}
	private void step4() {
		System.out.println(String.format("%s_执行步骤四..", this.getClass().getSuperclass().getSimpleName()));
	}
	protected abstract void step5();
}

2.实现变化方法

package com.lius.patternDesign.templateMethod;

public class templateMethodItem extends templateMethod {

	@Override
	protected void step2() {
		// TODO Auto-generated method stub
		System.out.println(String.format("%s_方法2执行...", this.getClass().getSimpleName()));
	}

	@Override
	protected void step5() {
		// TODO Auto-generated method stub
		System.out.println(String.format("%s_方法5执行...", this.getClass().getSimpleName()));
	}

	//主程序入口
	public static void main(String[] args) {
		templateMethodItem tem = new templateMethodItem();
		tem.run();//执行函数主流程
	}
}

 

你可能感兴趣的:(设计模式,设计模式,java,templates)