1. 作用
模板模式:定义父类,start方法(本文以该方法为例)定义所有抽象方法的执行顺序,子类覆写抽象方法
2. 代码
2.1 功能类
package com.hz.design.template;
/**
* @fileName: Game
* @version:
* @description:
* @author: pp_lan
* @date: 2022/3/31
*/
public abstract class Employee {
protected abstract void initialize();
protected abstract void clockIn();
protected abstract void work();
/**
* 模板,定义执行顺序
*/
public final void start() {
initialize();
clockIn();
work();
}
}
package com.hz.design.template;
/**
* @fileName: Programmer
* @version:
* @description: 程序员
* @author: pp_lan
* @date: 2022/3/31
*/
public class Programmer extends Employee {
private String name;
public Programmer(String name) {
this.name = name;
}
@Override
protected void initialize() {
System.out.format("程序员 %s 起床到达公司.\n", this.name);
}
@Override
protected void clockIn() {
System.out.format("程序员 %s 打开OA,打卡签到.\n", this.name);
}
@Override
protected void work() {
System.out.format("程序员 %s 打开IDEA开始工作.\n", this.name);
}
}
package com.hz.design.template;
/**
* @fileName: HR
* @version:
* @description: HR
* @author: pp_lan
* @date: 2022/3/31
*/
public class HR extends Employee {
private String name;
public HR(String name) {
this.name = name;
}
@Override
protected void initialize() {
System.out.format("HR %s 起床到达公司.\n", this.name);
}
@Override
protected void clockIn() {
System.out.format("HR %s 打开OA,打卡签到.\n", this.name);
}
@Override
protected void work() {
System.out.format("HR %s 拿起手机开始打电话.\n", this.name);
}
}
2.2 测试类
package com.hz.design.template;
/**
* @fileName: TemplateTest
* @version:
* @description: 模板模式:定义父类,start方法定义所有抽象方法的执行顺序,子类覆写抽象方法
* @author: pp_lan
* @date: 2022/3/31
*/
public class TemplateTest {
public static void main(String[] args) {
Programmer programmer = new Programmer("zhangsan");
HR hr = new HR("lili");
programmer.start();
System.out.println("=============================");
hr.start();
}
}
3. 执行结果
程序员 zhangsan 起床到达公司.
程序员 zhangsan 打开OA,打卡签到.
程序员 zhangsan 打开IDEA开始工作.
=============================
HR lili 起床到达公司.
HR lili 打开OA,打卡签到.
HR lili 拿起手机开始打电话.