软件原型模式

  • 原型模式
    • 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    • 例子 :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);
    }
}
相关推荐
想吃火锅100512 天前
【前端手撕】instanceof
前端·javascript·原型模式
UXbot12 天前
帮助企业低门槛开展AI应用开发的平台推荐
前端·低代码·ui·交互·产品经理·原型模式·web app
UXbot12 天前
如何选择适合公司项目的UI设计工具?企业选型指南
前端·低代码·ui·团队开发·原型模式·设计规范·web app
UXbot12 天前
原型设计工具如何帮助新人快速进入产品行业?
前端·低代码·ui·交互·团队开发·原型模式·web app
sunny.day17 天前
js原型与原型链
开发语言·javascript·原型模式·js原型链
UXbot18 天前
AI网页开发工具能替代工具吗?5大平台对比
前端·人工智能·低代码·ui·原型模式·web app
weixin_3077791318 天前
从“大海捞针”到“主动推理”:AI如何重塑云原生故障诊断的根因链
开发语言·人工智能·算法·自动化·原型模式
swordbob18 天前
prototype 注入到 singleton 里,prototype是否还是线程安全的
安全·spring·单例模式·原型模式
isNotNullX19 天前
企业数据中台建设,ETL工具选错了会踩哪些坑?
数据仓库·etl·原型模式
半个烧饼不加肉19 天前
JS 底层探究-- 普通函数和构造函数
开发语言·javascript·原型模式