Java设计模式 —— 原型模式(Prototype)

版权声明:本文为博主经验积累 https://blog.csdn.net/qq_23452385/article/details/89285573

Java设计模式 —— 原型模式(Prototype)

定义

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

特征:

  1. 原型模式是通过拷贝一个现有对象生成新对象的。
  2. 浅拷贝实现 Cloneable 接口重写,通过 clone 的方法创建一个对象
  3. 深拷贝是通过实现 Serializable 读取二进制流

代码实现

实现了 Cloneable 接口的抽象类

public class Shape implements Cloneable {
    private String id;
    private ArrayList mImages = new ArrayList<>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void addImages(String image) {
        this.mImages.add(image);
    }

    public ArrayList getmImages() {
        return mImages;
    }

    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

clone 生成对象

Shape shape = new Shape();
shape.setId("shape");
Shape shape1 = (Shape) shape.clone();

原型模式使用问题

1、通过clone拷贝对象的时候并不会执行构造函数。如果在构造函数中有需要一些特殊的初始化,在使用Cloneable实现拷贝的时候,需要注意这一点。
2、clone拷贝是一个浅拷贝,也叫影子拷贝,这种拷贝实际上并不是将原始文档的所有字段都重新构造一份,而是将副本文档的字段引用原始文档的字段。

Shape shape = new Shape();
Shape shape1 = (Shape) shape.clone();
shape1.addImages("Rectangle");

System.out.println("shape Id:" + shape.getId());
System.out.println("Images List:" + shape.getmImages());

继承 Serializable 接口实现深拷贝

public Object deepClone() {
    try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(this);

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        return oi.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}

Android中的原型模式

Intent.java
xref: /frameworks/base/core/java/android/content/Intent.java
在这里插入图片描述

感谢

segmentfault: 原型模式
百度百科: 原型模式
掘金: Java 设计模式之原型模式

猜你喜欢

转载自blog.csdn.net/qq_23452385/article/details/89285573