设计模式之原型模式 - 深拷贝和浅拷贝

设计模式 Java 面试 About 2,086 words

作用

用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新的对象。

案例

浅拷贝

  • 实现Cloneable
  • 重写clone方法
  • 能拷贝基础类型及String
  • 不能拷贝引用类型
public class Prototype implements Cloneable {

    @Override
    protected Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

}

深拷贝

  • 实现Serializable、Cloneable
  • 使用ByteArrayOutputStream/ObjectOutputStream/ByteArrayInputStream/ObjectInputStream
public class DeepClonePrototype implements Serializable, Cloneable {

    public Helper helper;

    public DeepClonePrototype deepClone() throws Exception {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (DeepClonePrototype) ois.readObject();
        }
    }
}

class Helper implements Serializable {

}

运行结果

//create.prototype.Prototype@4554617c
//create.prototype.Prototype@74a14482
//--------------
//create.prototype.DeepClonePrototype@1540e19d
//create.prototype.Helper@677327b6
//create.prototype.DeepClonePrototype@7ef20235
//create.prototype.Helper@27d6c5e0
public static void main(String[] args) throws Exception {
    Prototype prototype = new Prototype();
    System.out.println(prototype);
    Prototype clone = prototype.clone();
    System.out.println(clone);

    System.out.println("--------------");

    DeepClonePrototype deepClonePrototype = new DeepClonePrototype();
    Helper helper = new Helper();
    deepClonePrototype.helper = helper;
    System.out.println(deepClonePrototype);
    System.out.println(helper);
    DeepClonePrototype clone2 = deepClonePrototype.deepClone();
    System.out.println(clone2);
    System.out.println(clone2.helper);
}

源码

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

Spring框架注入bean对象时指定scopeprototype

注解指定:@Scope("prototype")

xml配置指定:

<bean id="jedisUtil" class="com.demo.util.JedisUtil" scope="prototype"/>
Views: 2,537 · Posted: 2019-12-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh