软件原型模式

  • 原型模式
    • 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    • 例子 :Java中的Object.clone()方法。

以下是一个原型模式(Prototype Pattern)的 Java 实现示例,通过实现 Cloneable 接口并重写 clone() 方法来实现对象的拷贝:

java 复制代码
import java.util.ArrayList;
import java.util.List;

// 1. 定义原型类,实现 Cloneable 接口
class Prototype implements Cloneable {
    private String name;
    private List<String> items;

    public Prototype(String name, List<String> items) {
        this.name = name;
        this.items = items;
    }

    // 重写 clone 方法
    @Override
    public Prototype clone() {
        try {
            // 调用 Object.clone() 进行浅拷贝
            Prototype cloned = (Prototype) super.clone();
            // 对引用类型进行深拷贝
            cloned.items = new ArrayList<>(this.items);
            return cloned;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(); // 不会发生
        }
    }

    // 添加 item
    public void addItem(String item) {
        this.items.add(item);
    }

    @Override
    public String toString() {
        return "Prototype{" +
                "name='" + name + '\'' +
                ", items=" + items +
                '}';
    }
}

// 2. 客户端代码
public class PrototypePatternDemo {
    public static void main(String[] args) {
        // 创建原型对象
        List<String> initialItems = new ArrayList<>();
        initialItems.add("Item1");
        initialItems.add("Item2");
        Prototype original = new Prototype("Original", initialItems);

        // 克隆原型对象
        Prototype cloned = original.clone();

        // 修改克隆对象
        cloned.addItem("Item3");

        // 输出结果
        System.out.println("Original: " + original);
        System.out.println("Cloned: " + cloned);
    }
}
相关推荐
程序边界5 天前
一台数据集成软件的拆解笔记(上):把 KFS 装起来、跑起来,再挑一堆毛病
笔记·原型模式
General_G10 天前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
冒险的豆子15 天前
JS 原型链 通俗易懂 解释说明(类比 关系)
开发语言·javascript·原型模式
吠品23 天前
箭头函数为什么不能 new
开发语言·javascript·原型模式
2603_965896621 个月前
JS原型与原型链|对象继承与实例底层原理
开发语言·javascript·原型模式
YYYing.1 个月前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
羞儿2 个月前
【读点论文】Overall positive prototype for few-shot open-set recognition
原型模式·小样本学习·特征优化·开集学习
liangshanbo12152 个月前
手写 Function.prototype.call 与 Function.prototype.apply 面试题满分答案
开发语言·javascript·原型模式
江畔柳前堤2 个月前
云原生 × AI 全景图谱:从 Kubernetes 到 Agent 基础设施的一次认知跃迁
人工智能·分布式·gpt·云原生·kubernetes·原型模式·agi
艾伦野鸽ggg2 个月前
JavaScript 原型链与原型对象详解
javascript·原型模式