<aside> 💡

模板方法模式(TemplateMethod):定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤

</aside>

结构图

image.png

优缺点与应用场景

题目

https://kamacoder.com/problempage.php?pid=1087

#include <iostream>
using namespace std;

// 模板类
class Coffee{
public:
    // 模板方法
    virtual void makeCoffee() final {
        title();
        cout << "Grinding coffee beans" << endl;
        cout << "Brewing coffee" << endl;
        step3();
        cout << "Adding condiments\\n" << endl;
    }

protected:
    // 一些基本方法,定义了一些具体的实现步骤,由其子类负责实现
    virtual void title() = 0; 
    virtual void step3() = 0;
};

// 具体类
class AmericanCoffee: public Coffee{
    // 不同子类以不同方式重写基本方法
    void title() override {
        cout << "Making American Coffee:" << endl;
    }

    void step3() override {}
};

class Latte: public Coffee{
    void title() override {
        cout << "Making Latte:" << endl;
    }

    void step3() override {
        cout << "Adding milk" << endl;
    }
};

int main(){
    int coffeeType;
    Coffee* coffee = nullptr;
    while(cin >> coffeeType){
        switch(coffeeType){
        case 1:
            coffee = new AmericanCoffee();
            break;
        case 2:
            coffee = new Latte();
            break;
        default:
            cout << "请输入正确的咖啡种类:" << endl;
            return -1;
            break;
        }
        coffee->makeCoffee();
        delete coffee;
    }

    return 0;    
}