【设计模式】【创建型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 */
相关推荐
Wild_Pointer.3 小时前
设计模式实战精讲:全景目录
设计模式·设计规范
一叶飘零_sweeeet11 小时前
深度拆解汽车制造系统设计:用 Java + 设计模式打造高扩展性品牌 - 车型动态生成架构
java·设计模式·工厂设计模式
小毛驴85012 小时前
软件原型模式
原型模式
阿波罗尼亚13 小时前
设计原则(一)Head First设计模式
设计模式
谢尔登16 小时前
原型理解从入门到精通
开发语言·javascript·原型模式
ZHE|张恒1 天前
设计模式实战篇(五):责任链模式 — 把复杂审批/过滤流程变成可组合的“传递链”
设计模式·责任链模式
CodeAmaz1 天前
使用责任链模式设计电商下单流程(Java 实战)
java·后端·设计模式·责任链模式·下单
十一.3661 天前
66-69 原型对象,toString(),垃圾回收
开发语言·javascript·原型模式
大G的笔记本1 天前
Java常见设计模式面试题(高频)
java·开发语言·设计模式
老鼠只爱大米1 天前
Java设计模式之建造者模式(Builder)详解
java·设计模式·建造者模式·builder·23种设计模式