软件原型模式

  • 原型模式
    • 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    • 例子 :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);
    }
}
相关推荐
神奇霸王龙2 天前
Codex MCP GA 实测:Qwen / GLM / Kimi / DeepSeek / MiniMax 调度 Codex 沙箱的真实成本
人工智能·ai·agent·ai编程·原型模式·mcp
葡萄城技术团队3 天前
如何通过 JSON 数据源 / Web API 快速构建轻量级报表(Report)?
前端·json·原型模式
Leo.yuan4 天前
2026国内数据治理平台选型指南:从ETL到数据质量的一体化路径
原型模式
一个游离的指针17 天前
JS中的对象的相关概念
开发语言·javascript·原型模式
码哥DFS18 天前
构造函数、实例对象、对象原型 ----三者关系
开发语言·javascript·原型模式
lincats21 天前
AI Agent 工程化六层架构:从 Prompt 到 Production
人工智能·架构·prompt·知识图谱·原型模式·vibecoding·grillme
叶总没有会22 天前
5.1知识库概念进阶
java·人工智能·spring·阿里云·ai·原型模式
lincats22 天前
智能体工程 vs 软件工程:计算机系那套课程,还能适应 AI 时代吗?
人工智能·软件工程·原型模式·vibecoding·claudecode·grillme
ltqvibe1 个月前
数据中台为什么走不通——本体语义给出的替代路径
人工智能·原型模式·本体语义平台
啦啦啦啦啦zzzz1 个月前
设计模式:原型模式
c++·设计模式·原型模式