设计模式【十四】-模板模式

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 拿起手机开始打电话.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值