码迷,mamicode.com
首页 > 其他好文 > 详细

模板模式

时间:2019-04-18 14:45:33      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:ext   this   xtend   ret   cond   new   add   介绍   img   

介绍

流程标准化,但具体的原料(功能)自己实现。
如:泡茶有以下四个步骤: 1、 烧开水; 2 、把茶放到水杯中; 3、倒入开水; 4、可以什么都不干。
  泡咖啡也有以下四个步骤: 1、 烧开水; 2、 把咖啡放到水杯中; 3、倒入开水; 4、 加入糖和牛奶。

程序

public abstract class AbstractTemplate {

    public final void template(){
        this.boilWater();
        this.putIntoCup();
        this.addHotWater();
        if (isCustomered()) {
            // 加入调料
            this.addCondiments();

        }

    }
    private void boilWater() {
        System.out.println("烧开水");
    }

    protected abstract void putIntoCup();

    private void addHotWater() {
        System.out.println("加水");
    }
    protected abstract void addCondiments();
    // 钩子函数
    protected boolean isCustomered() {
        return true;
    }
}

因为流程中某一个环节可以省略,我们可以增加钩子函数来确认是否需要定制
```java
public class Coffee extends AbstractTemplate{
protected void putIntoCup() {
System.out.println("把咖啡放水杯里");
}

protected void addCondiments() {
    System.out.println("加糖加奶");
}

}
java
public class Tea extends AbstractTemplate{
protected void putIntoCup() {
System.out.println("把茶叶放水杯里");
}

protected void addCondiments() {
    System.out.println("加点***");
}

protected boolean isCustomered() {
    return false;
}

}
测试下:java
// 咖啡制作
AbstractTemplate coffee = new Coffee();
coffee.template();
System.out.println("-------------------");
// 茶制作
AbstractTemplate tea = new Tea();
tea.template();
```
结果:
技术图片

模板模式

标签:ext   this   xtend   ret   cond   new   add   介绍   img   

原文地址:https://www.cnblogs.com/guomomo/p/10729359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!