软件原型模式

  • 原型模式
    • 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    • 例子 :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);
    }
}
相关推荐
bmseven7 天前
23种设计模式 - 原型模式(Prototype)
设计模式·原型模式
Amumu1213811 天前
Js: 构造函数、继承、面向对象
原型模式
砍光二叉树12 天前
【设计模式】创建型-原型模式
设计模式·原型模式
RFCEO13 天前
JavaScript基础课程十四、原型与原型链(JS 核心底层)
开发语言·原型模式·prototype原型详解·javascript基础课·构造函数原型方法定义与使用·js原型链继承机制入门·t原型链顶层null原理
new code Boy13 天前
前端核心基础汇总
开发语言·javascript·原型模式
爱写bug的野原新之助14 天前
爬虫之补环境脚本:脱环境
javascript·爬虫·原型模式
承缘丶16 天前
使用http调用Kettle资源库中的ETL任务
原型模式
夕珩19 天前
单例模式、原型模式、工厂方法模式、抽象工厂模式、建造者模式、解释器模式、命令模式
单例模式·解释器模式·建造者模式·工厂方法模式·抽象工厂模式·命令模式·原型模式
TON_G-T21 天前
JavaScript 原型与原型链
开发语言·javascript·原型模式
蜜獾云21 天前
设计模式之原型模式:以自己为原型,自己实现自己的对象拷贝逻辑
java·设计模式·原型模式