设计模式(4)-原型模式及实现
基本概念
通过复制现有对象来创建新对象,而不是从头开始构建。这允许我们以更高效的方式创建新对象,同时避免了与对象类的直接耦合。核心概念是在原型对象的基础上进行克隆,使得新对象具有与原型相同的初始状态。
优点:
● 减少对象创建的成本:避免了复杂对象的重复初始化过程,提高了创建对象的效率。
● 避免与具体类耦合:客户端可以通过克隆方法创建新对象,而无需知道具体类的细节,降低了耦合度。
● 灵活性增加:可以在运行时动态地添加或删除原型,适应不同的对象创建需求。
● 支持动态配置:可以通过克隆来定制对象的不同配置,而无需修改其代码。
缺点:
● 深克隆问题:原型模式默认进行浅克隆,即复制对象本身和其引用。如果对象内部包含其他对象的引用,可能需要实现深克隆来复制整个对象结构。
● 克隆方法的实现:某些对象可能不容易进行克隆,特别是涉及到文件、网络连接等资源的情况。
https://gitee.com/want-to-lose-another-30-jin/design-pattern-implementation
设计模式具体实现
角色
1、原型接口(Prototype Interface):声明一个克隆自身的操作,通常是一个clone()方法。
2、具体原型类(Concrete Prototype):实现原型接口,并实现克隆操作,返回对象的一个副本。
3、客户端(Client):负责创建和请求对象,通过使用克隆操作来复制已有对象。
java实现
package com.shejimoshi.yuanxingmoshi;
// 定义一个原型接口
public interface Prototype extends Cloneable {
Prototype clone(); // 声明克隆方法
}
package com.shejimoshi.yuanxingmoshi;
public class ConcretePrototype implements Prototype {
private String type;
public ConcretePrototype(String type) {
this.type = type;
}
@Override
public Prototype clone() {
try {
return (ConcretePrototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
package com.shejimoshi.yuanxingmoshi;
public class client {
public static void main(String[] args) {
Prototype myPrototype = new ConcretePrototype("Type A");
Prototype clonedPrototype = myPrototype.clone();
System.out.println("Original: " + myPrototype);
System.out.println("Cloned: " + clonedPrototype);
}
}
c++实现
#include <iostream>
#include <string>
using namespace std;
// 原型接口
class Prototype {
public:
virtual ~Prototype() {}
virtual Prototype* clone() const = 0; // 纯虚函数,声明克隆方法
};
// 具体原型类
class ConcretePrototype : public Prototype {
private:
std::string type;
public:
ConcretePrototype(const std::string& type) : type(type) {}
// 实现克隆方法
ConcretePrototype* clone() const override {
return new ConcretePrototype(*this);
}
void display() const {
std::cout << "Prototype Type: " << type << std::endl;
}
};
// 客户端代码
int main() {
ConcretePrototype* original = new ConcretePrototype("Type A");
ConcretePrototype* cloned = original->clone();
cout << original << endl;
cout << cloned << endl;
cloned->display();
delete original;
delete cloned;
return 0;
}