【设计模式】【创建型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 */
相关推荐
会员果汁3 小时前
17.设计模式-单例模式(Singleton)
单例模式·设计模式
派大鑫wink4 小时前
【Day37】MVC 设计模式:原理与手动实现简易 MVC 框架
java·设计模式·mvc
会员果汁4 小时前
18.设计模式-桥接模式
设计模式·桥接模式
老蒋每日coding4 小时前
AI Agent 设计模式系列(九)——学习和适应模式
人工智能·学习·设计模式
da_vinci_x18 小时前
武器设计实战:一把大剑裂变 5 种属性?Structure Ref 的“换肤”魔法
游戏·3d·设计模式·ai作画·aigc·设计师·游戏美术
方见华Richard21 小时前
自指宇宙学:存在如何通过自我描述而实在化V0.2
人工智能·交互·原型模式·空间计算
刀法孜然1 天前
23种设计模式 3 行为型模式 之3.7 command 命令模式
设计模式·命令模式
一条闲鱼_mytube1 天前
智能体设计模式(二)反思-工具使用-规划
网络·人工智能·设计模式
老蒋每日coding1 天前
AI智能体设计模式系列(七)—— 多 Agent 协作模式
设计模式
小码过河.1 天前
设计模式——代理模式
设计模式·代理模式