【设计模式】【创建型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 */
相关推荐
瑶池酒剑仙1 天前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
HarmonSir3 天前
Codex 架构解析:一条对话如何长成一个运行时系统
后端·设计模式·架构
饮水桶_T4 天前
Java调用大语言模型 笔记
笔记·设计模式·电脑·ai编程
ssshooter5 天前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式
饮水桶_T5 天前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AI酒旅实战开发6 天前
旅行 AI Agent 的 7 种设计模式:从工具调用到交易闭环
人工智能·设计模式
geovindu8 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu9 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh14 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊15 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式