【设计模式】【创建型5-5】【原型模式】

文章目录

原型模式

代码使用:spring框架里 bean的作用域

用途,以原型为模板,源源不断的创建(克隆 clone)对象。当直接创建对象的代价比较大时,则采用这种模式。

代码示例

java 复制代码
public class Human implements Cloneable{
    private int age;
    private String name;
    private int sex;
    public Human(int age, String name, int sex) {
        this.age = age;
        this.name = name;
        this.sex = sex;
    }
    @Override
    protected Human clone() {
        Human human = null;

        try {
            human = (Human) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e);
        }
        return human;
    }
}

class PrototypeMap {
    Map<String, Human> prototypeMap = new HashMap<>();
    public PrototypeMap() {
        // 初始化
        this.prototypeMap.put("Human", new Human(100, "666", 1));
    }
    public Object add(String k, Human v) {
        this.prototypeMap.put(k, v);
        return v;
    }
    public Human get(String k){
        Human o = this.prototypeMap.get(k);
        return o== null? o:o.clone();
    }
}
// 验证 原型模式 每次都返回出对象的克隆 且不同 虽然是浅克隆(深克隆 可以使用输入输出流 序列化反序列化)
    public static void main(String[] args) {
        PrototypeMap prototypeMap = new PrototypeMap();
        Human human1 = prototypeMap.get("Human");
        Human human2 = prototypeMap.get("Human");
        System.out.println(human1);
        System.out.println(System.identityHashCode(human1));
        System.out.println(human2);
        System.out.println(System.identityHashCode(human2));
    }
/*
Human{age=100, name='666', sex=1}
285377351
Human{age=100, name='666', sex=1}
344560770 */
相关推荐
方见华Richard5 小时前
世毫九实验室(Shardy Lab)研究成果清单(2025版)
人工智能·经验分享·交互·原型模式·空间计算
苏渡苇6 小时前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·设计模式·学习方法·责任链模式
短剑重铸之日7 小时前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
feasibility.7 小时前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
BD_Marathon8 小时前
七大设计原则介绍
设计模式
YigAin10 小时前
Unity23种设计模式之 享元模式
设计模式·享元模式
方见华Richard10 小时前
世毫九实验室技术优势拆解与对比分析(2026)
人工智能·交互·学习方法·原型模式·空间计算
范纹杉想快点毕业1 天前
实战级ZYNQ中断状态机FIFO设计
java·开发语言·驱动开发·设计模式·架构·mfc
茂桑1 天前
DDD领域驱动设计-基础设施层
设计模式·架构
方见华Richard1 天前
AGI安全三大方向机构对比清单(2025-2026)
人工智能·经验分享·交互·原型模式·空间计算