4.设计模式名称:原型模式(Prototype)
概念
原型模式是一种创建型设计模式,它用于创建对象,通过复制一个已经存在的对象来创建新的对象,而不是通过实例化。原型模式允许你复制已有的对象,而无需使代码依赖它们所属的类。
意图
- 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
- 通过克隆来生成对象,而不是通过构造函数。
适用性
- 当一个系统应该独立于它的产品创建、构成和表示时。
- 当要实例化的类是在运行时决定的时候,例如,通过动态加载。
- 当避免创建一个与产品类层次平行的工厂类层次结构时。
结构
原型模式通常涉及以下几个角色:
- Prototype:声明一个克隆自身的接口。
- ConcretePrototype:实现 Prototype 接口的具体类,负责实现克隆自身的操作。
- Client:使用原型对象的客户端。
实现代码示例
以下是使用 C++ 实现原型模式的示例,其中定义了一个 Shape
接口作为原型,以及具体的 Circle
和 Square
类来实现克隆操作。
#include <iostream>
#include <unordered_map>
// Prototype
class Shape {
public:
virtual Shape *clone() const = 0;
virtual void draw() const = 0;
virtual ~Shape() {}
};
// Concrete Prototypes
class Circle : public Shape {
public:
Shape *clone() const override {
return new Circle(*this);
}
void draw() const override {
std::cout << "Drawing a circle" << std::endl;
}
};
class Square : public Shape {
public:
Shape *clone() const override {
return new Square(*this);
}
void draw() const override {
std::cout << "Drawing a square" << std::endl;
}
};
// Client
class ShapeCache {
private:
std::unordered_map<std::string, Shape *> cache;
public:
Shape *getShape(const std::string &type) const {
return cache.at(type)->clone();
}
void loadCache() {
cache["Circle"] = new Circle();
cache["Square"] = new Square();
}
~ShapeCache() {
for (auto &it: cache) {
delete it.second;
}
}
};
int main() {
ShapeCache cache;
cache.loadCache();
Shape *clonedShape1 = cache.getShape("Circle");
Shape *clonedShape2 = cache.getShape("Square");
clonedShape1->draw();
clonedShape2->draw();
delete clonedShape1;
delete clonedShape2;
return 0;
}
输出
Drawing a circle
Drawing a square
在这个例子中,Shape
接口是原型,Circle
和 Square
是具体的原型类,它们实现了 clone()
方法来返回自身的副本。ShapeCache
类负责创建和管理原型对象的缓存,客户端可以通过 getShape()
方法来获取克隆的对象。这种模式能够在运行时动态地添加或删除原型,同时避免了直接依赖具体类的实例化。