此为设计模式第四谈!
用总-分-总的结构和生活化的例子给你讲解设计模式!
码农不易,各位学者学到东西请点赞收藏支持支持!
开始部分:
总:原型模式的核心逻辑在于通过克隆现有实例来创建新对象,而不是通过传统的构造函数,根据需求来修改属性。
分:
1.老规矩,打开VS创建一个控制台应用
2.实现编码,这里用制作三明治为讲解例子
2.1 创建抽象原型基类
2.2 实现原型类的克隆逻辑
2.3 创建原型实例
2.4 克隆对象
2.5 使用克隆对象
#include <iostream>
#include <map>
#include <string>
#include <vector>
//1.创建抽象基类
class Sandwich {
public:
Sandwich(std::string bread, std::string sauce, std::vector<std::string> toppings)
: _bread(bread), _sauce(sauce), _toppings(toppings) {}
virtual Sandwich* clone() const = 0;//clone纯虚函数,用于克隆对象
virtual void display() const = 0;//用于展示三明治属性
protected:
std::string _bread;//面包类型
std::string _sauce;//酱汁类型
std::vector<std::string> _toppings;//配料
};
//经典火腿三明治类
class HamSandwich : public Sandwich {
public:
HamSandwich(std::string bread, std::string sauce, std::vector<std::string> toppings)
: Sandwich(bread, sauce, toppings) {}//子类调用基类构造函数
Sandwich* clone() const override {//重写clone方法,常量成员函数,不会修改调用该函数的对象的任何成员变量
return new HamSandwich(*this);
}
void display() const override {
std::cout << "Ham Sandwich - Bread: " << _bread
<< ", Sauce: " << _sauce
<< ", Toppings: ";
for (const auto& topping : _toppings) {
std::cout << topping << ' ';
}
std::cout << std::endl;
}
};
//意式蔬菜三明治类
class VeggieSandwich : public Sandwich {
public:
VeggieSandwich(std::string bread, std::string sauce, std::vector<std::string> toppings)
: Sandwich(bread, sauce, toppings) {}
Sandwich* clone() const override {
return new VeggieSandwich(*this);
}
void display() const override {
std::cout << "Veggie Sandwich - Bread: " << _bread
<< ", Sauce: " << _sauce
<< ", Toppings: ";
for (const auto& topping : _toppings) {
std::cout << topping << ' ';
}
std::cout << std::endl;
}
};
int main() {
// 建立“原型”三明治
Sandwich* hamPrototype = new HamSandwich("White", "Mayo",
{"Ham", "Lettuce", "Tomato"});
Sandwich* veggiePrototype = new VeggieSandwich("Wheat", "Pesto",
{"Cucumber", "Avocado"});
// 复制并个性化
Sandwich* customerOrder1 = hamPrototype->clone(); // 点单经典火腿三明治
customerOrder1->_sauce = "Mustard"; // 添加个人偏好
customerOrder1->_toppings.push_back("Cheese");
Sandwich* customerOrder2 = veggiePrototype->clone(); // 点单经典意式蔬菜三明治
customerOrder2->_bread = "Sourdough"; // 更改面包
customerOrder2->_toppings.push_back("Olives");
// 展示订单
customerOrder1->display();
customerOrder2->display();
// 清理
delete hamPrototype;
delete veggiePrototype;
delete customerOrder1;
delete customerOrder2;
return 0;
}