小工具知识网

当前位置: 首页 > 行业知识 > 【设计模式 05】原型模式

行业知识

【设计模式 05】原型模式

2026-11-17 02:24:14 来源:互联网转载

���的时候,我们创建对象,需要耗费大量时间在一些资源型操作上,这个时候,我们就可以先创建出一个模板,然后每次创建的时候直接从模板复制即可,不用反复进行耗时的资源型操作。

python代码:

import copyclass ComplexObject:    def __init__(self, data):        # 资源型操作         self.data = data        def clone(self):        # 复制        return copy.deepcopy(self)# 创建原型对象obj1 = ComplexObject(data = "large data")# 创建新对象,直接拷贝原对象new_object = original_object.clone()

 

JAVA代码:

// 1. 定义抽象原型类public abstract class Prototype  implements Coneable {    public abstract Prototype clone();}// 2. 定义具体原型类public class ConcretePrototype extends Prototype {    private String data;    public ConcretePrototype(String data) {        this.data = data;    }    @Override    public Prototype clone() {        return new ConcretePrototype(this.data);    }    public String getData() {        return data;    }}// 3. 客户端代码public class Client {    public static void main(String[] args) {        // 创建原型对象        Prototype original = new ConcretePrototype("原始对象");        // 克隆原型对象        Prototype clone = original.clone();        // 输出克隆对象的数据        System.out.println("Clone Data: " + ((ConcretePrototype) clone).getData());    }}

 【设计模式专题之原型模式】5. 矩形原型

#include#include#includeusing namespace std;// 抽象原型类class Prototype {public:    virtual Prototype* clone() const = 0;    virtual string getDetails() const = 0;    virtual ~Prototype() {}};// 具体矩形原型类class RectanglePrototype : public Prototype {private:    string color;    int width;    int height;public:    // 构造方法    RectanglePrototype(const string& color, int width, int height) : color(color), width(width), height(height) {}    // 克隆方法    Prototype* clone() const override {        return new RectanglePrototype(*this);    }    string getDetails() const override {        return "Color: " + color + ", Width: " + to_string(width) + ", Height: " + to_string(height);    }};// 客户端 int main() {    vector rectangles;    // 读取需要创建的矩形数量    int N;    cin >> N;    // 地区每个矩形的属性星系并创建矩形对象    for (int i = 0; i > color >> width >> height;        // 创建原型对象        Prototype* originalRectangle = new RectanglePrototype(color, width, height);        // 将原型对象保存到向量中        rectangles.push_back(originalRectangle);    }    // 克隆对象    for (const auto& rectangle : rectangles) {        Prototype* cloneRectangle = rectangle->clone();        cout getDetails() 

上一篇:关键词优化秘籍,提升内容吸引力,轻松提升点击率!

下一篇:服务器怎么设置存储阀值?