【设计模式】【创建型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 */
相关推荐
Asort1 小时前
JavaScript设计模式(十七)——中介者模式 (Mediator):解耦复杂交互的艺术与实践
前端·javascript·设计模式
czy87874752 小时前
软件设计模式
设计模式
Hero | 柒2 小时前
设计模式之单例模式
java·单例模式·设计模式
W.Buffer3 小时前
设计模式-工厂模式:解耦对象创建的设计艺术
java·开发语言·设计模式
WaWaJie_Ngen3 小时前
【设计模式】建造者模式(Builder)
设计模式·建造者模式
筏.k5 小时前
C++ 设计模式系列:生产者-消费者模式完全指南
开发语言·c++·设计模式
Tiny_React17 小时前
智能体设计模式-附录 C - 智能体框架快速概览
设计模式
YBN娜19 小时前
设计模式-创建型设计模式
java·开发语言·设计模式
YuanlongWang20 小时前
C# 设计模式——单例模式
单例模式·设计模式·c#
Code_Geo21 小时前
agent设计模式:第二章节—路由
网络·设计模式·路由