汇总目录请点击访问:《设计模式目录汇总》 喜欢内容的话欢迎关注、点赞、收藏!感谢支持,祝大家祉猷并茂,顺遂无虞!
原型模式(Prototype Pattern)是一种创建型设计模式,它允许通过复制已有对象来创建新对象,而不是直接通过实例化类来创建。 这种模式提供了一种创建对象的快捷方式,尤其适用于对象创建成本高或需要深复制的场景。
在图形化编辑器中复制图形或文档内容。
复制已有的数据记录以快速生成新记录。
玩家角色或敌人角色的复制,避免重复初始化。
#include <iostream>
#include <memory>
#include <string>
// 抽象原型
class Prototype {
public:
virtual std::unique_ptr<Prototype> clone() const = 0;
virtual void display() const = 0;
virtual ~Prototype() = default;
};
// 具体原型 1
class ConcretePrototypeA : public Prototype {
std::string state;
public:
ConcretePrototypeA(const std::string& s) : state(s) {}
std::unique_ptr<Prototype> clone() const override {
return std::make_unique<ConcretePrototypeA>(*this); // 浅复制
}
void display() const override {
std::cout << "ConcretePrototypeA with state: " << state << std::endl;
}
};
// 具体原型 2
class ConcretePrototypeB : public Prototype {
int value;
public:
ConcretePrototypeB(int v) : value(v) {}
std::unique_ptr<Prototype> clone() const override {
return std::make_unique<ConcretePrototypeB>(*this); // 浅复制
}
void display() const override {
std::cout << "ConcretePrototypeB with value: " << value << std::endl;
}
};
// 客户端代码
int main() {
std::unique_ptr<Prototype> prototypeA = std::make_unique<ConcretePrototypeA>("Initial State");
std::unique_ptr<Prototype> cloneA = prototypeA->clone();
cloneA->display();
std::unique_ptr<Prototype> prototypeB = std::make_unique<ConcretePrototypeB>(42);
std::unique_ptr<Prototype> cloneB = prototypeB->clone();
cloneB->display();
return 0;
}using System;
// 抽象原型
public abstract class Prototype {
public abstract Prototype Clone();
public abstract void Display();
}
// 具体原型 1
public class ConcretePrototypeA : Prototype {
private string State;
public ConcretePrototypeA(string state) {
State = state;
}
public override Prototype Clone() {
return (Prototype)this.MemberwiseClone(); // 浅复制
}
public override void Display() {
Console.WriteLine($"ConcretePrototypeA with state: {State}");
}
}
// 具体原型 2
public class ConcretePrototypeB : Prototype {
private int Value;
public ConcretePrototypeB(int value) {
Value = value;
}
public override Prototype Clone() {
return (Prototype)this.MemberwiseClone(); // 浅复制
}
public override void Display() {
Console.WriteLine($"ConcretePrototypeB with value: {Value}");
}
}
// 客户端代码
class Program {
static void Main(string[] args) {
Prototype prototypeA = new ConcretePrototypeA("Initial State");
Prototype cloneA = prototypeA.Clone();
cloneA.Display();
Prototype prototypeB = new ConcretePrototypeB(42);
Prototype cloneB = prototypeB.Clone();
cloneB.Display();
}
}
将原型对象注册到一个集中管理的注册表中,客户端可以通过键值对直接获取克隆。
特性 | 原型模式 | 工厂模式 |
|---|---|---|
关注点 | 通过复制现有对象创建新对象 | 通过实例化类创建对象 |
适用场景 | 对象初始化复杂或需要复制时 | 创建独立新对象时 |
灵活性 | 更高(动态克隆对象) | 较低(需修改工厂实现) |
原型模式通过复制已有对象,提供了一种高效的对象创建方式,适合对象初始化开销高或需要频繁复制的场景。其核心在于克隆方法的实现,正确处理深浅复制关系是关键。在实践中,原型模式通常与其他模式结合使用,如工厂模式、注册表模式,进一步提高代码的灵活性和复用性。
欢迎关注、点赞、收藏!更多系列内容可以点击专栏目录订阅,感谢支持,再次祝大家祉猷并茂,顺遂无虞!
若将文章用作它处,请一定注明出处,商用请私信联系我!