【设计模式】【创建型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 */
相关推荐
是2的10次方啊1 小时前
设计模式与生活⑰:空腹体检,单子领着人走
设计模式
是2的10次方啊17 小时前
设计模式与生活⑯:天冷了,出门这身得一层层配
设计模式
心若自由何处是束缚1 天前
适配器模式:从原理到实战的完整指南
设计模式·适配器模式
是2的10次方啊2 天前
设计模式与生活⑮:看到哪儿了,得有个地方替你记着
设计模式
2601_967979122 天前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
是2的10次方啊3 天前
设计模式与生活⑭:一栋楼,共用一份热
设计模式
是2的10次方啊4 天前
设计模式与生活⑬:你坐几号线,谁来运营是另一回事
设计模式
Tt有了t5 天前
设计模式速查
java·python·设计模式
一条Go5 天前
四个进程,一把锁:Alioth 的告警评测为什么不需要消息队列
后端·设计模式·架构
一缕82年的清风5 天前
被中产唾弃的“十元快剪”,藏着最狠的极客工程学
人工智能·设计模式