【C++】【设计模式】模板方法模式

该代码示例展示了如何使用C++实现模板方法设计模式来模拟咖啡和茶的制作过程。CaffeineBeverage类定义了一个基本的制作流程,包括煮水、冲泡和倒入杯中,并提供了钩子方法来确定是否需要添加调料。Coffee和Tea子类实现了具体的冲泡和添加调料步骤,并可选择性地覆盖钩子方法以适应用户口味。
摘要由CSDN通过智能技术生成

【C++】【设计模式】模板方法模式(Template Method Pattern)

定义

  • 行为设计模式
  • 一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行

结构

  • 抽象类: 定义算法模版方法
  • 具体子类:继承并实现具体的模版方法(有选择性的)

UML类图

在这里插入图片描述

Demo源码

#include <iostream>
#include <memory>
using namespace std;

class CaffeineBeverage {
public:
    virtual ~CaffeineBeverage() {}
    // 模板方法,不允许子类修改
    void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        if (customerWantsCondiments()) {
            addCondiments();
        }
    }
 
    // 抽象方法,需要子类实现
    virtual void brew() const = 0;
    virtual void addCondiments() const = 0;
 
    // 具体方法,不允许子类修改
    void boilWater() const {
        cout << "Boiling water" << endl;
    }
 
    void pourInCup() const {
        cout << "Pouring into cup" << endl;
    }
 
    // 钩子方法,子类可以选择性的覆盖
    virtual bool customerWantsCondiments() const {
        return true;
    }
};
 
class Coffee : public CaffeineBeverage {
public:
    // 实现抽象方法
    void brew() const override {
        cout << "Dripping Coffee through filter" << endl;
    }
 
    void addCondiments() const override {
        cout << "Adding Sugar and Milk" << endl;
    }
 
    // 重载钩子方法
    bool customerWantsCondiments() const override {
        char answer;
        cout << "Would you like milk and sugar with your coffee (y/n)? " << endl;
        cin >> answer;
        return answer == 'y' || answer == 'Y';
    }
};
 
class Tea : public CaffeineBeverage {
public:
    // 实现抽象方法
    void brew() const override {
        cout << "Steeping the tea" << endl;
    }
 
    void addCondiments() const override {
        cout << "Adding Lemon" << endl;
    }
 
    // 重载钩子方法
    bool customerWantsCondiments() const override {
        char answer;
        cout << "Would you like lemon with your tea (y/n)? " << endl;
        cin >> answer;
        return answer == 'y' || answer == 'Y';
    }
};

int main() {
    auto coffee = make_unique<Coffee>();
    coffee->prepareRecipe();
    cout << endl;

    auto tea = make_unique<Tea>();
    tea->prepareRecipe();
    cout << endl;
 
    return 0;
}

分析总结

  • 代码复用、符合开闭原则、不变部分稳定,易于拓展
  • 增加类的数目
  • 是多态的一种应用体现
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值