1. 原型模式介绍

  创建对象的种类,并且通过拷贝这些原型,创建新的对象,无需知道如何创建的细节

 

2. 原型模式

  问题:现在有一只羊 tom ,姓名为 : tom, 年龄为: 1 ,颜色为:白色,请编写程序创建和 tom羊属性完全相同的10 只羊

  (1)传统方式解决

public class Sheep {

    private String name;

    private String color;

    private int age;

    public Sheep(String name, String color, int age) {
        this.name = name;
        this.color = color;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Client {

    public static void main(String[] args) {

        Sheep sheep = new Sheep("tome", "白色", 1);

        Sheep sheep1 = new Sheep(sheep.getName(), sheep.getColor(), sheep.getAge());
        Sheep sheep2 = new Sheep(sheep.getName(), sheep.getColor(), sheep.getAge());
        Sheep sheep3 = new Sheep(sheep.getName(), sheep.getColor(), sheep.getAge());

        System.out.println(sheep);
        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);
    }
}

  优点:比较好理解,简单易操作

  缺点:在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率较低;总是需要重新初始化对象,而不是动态地获得对象运行时的状态, 不够灵活

  (2)原型模式(浅拷贝)

public class Sheep implements Cloneable {

    private String name;

    private String color;

    private int age;

    public Sheep friend;

    public Sheep(String name, String color, int age) {
        this.name = name;
        this.color = color;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    protected Object clone(){
        Sheep sheep = null;

        try {
            sheep = (Sheep) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return sheep;
    }
}
public class Client {
    public static void main(String[] args) {

        Sheep sheep = new Sheep("tome", "白色", 1);
        sheep.friend = new Sheep("jack","褐色",1);
        Sheep sheep1 = (Sheep) sheep.clone();
        Sheep sheep2 = (Sheep) sheep.clone();

        System.out.println("sheep =" + sheep + "sheep.friend=" + sheep.friend.hashCode());
        System.out.println("sheep1 =" + sheep1 + "sheep1.friend=" + sheep1.friend.hashCode());
        System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());

    }
}

   (1)对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。

  (2)对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值

  (3)sheep.friend浅拷贝后还是都指向同一个内存地址

 

  (3)原型模式(深拷贝-重写clone方法)

public class DeepCloneableTarget implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;

    private String cloneName;

    private String cloneClass;

    public DeepCloneableTarget(String cloneName, String cloneClass) {
        this.cloneName = cloneName;
        this.cloneClass = cloneClass;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class DeepProtoType implements Serializable,Cloneable {

    public String name;

    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        deep = super.clone();
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget  = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deepProtoType;
    }
}
public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {

        DeepProtoType d = new DeepProtoType();
        d.name = "kater";
        d.deepCloneableTarget = new DeepCloneableTarget("ke","le");

        DeepProtoType d1 = (DeepProtoType) d.clone();
        System.out.println("d.name=" + d.name + " d.deepCloneableTarget=" + d.deepCloneableTarget.hashCode());
        System.out.println("d1.name=" + d1.name + " d1.deepCloneableTarget=" + d1.deepCloneableTarget.hashCode());

    }
}

 

  (4)原型模式(深拷贝-对象序列化)推荐

  使用对象序列化的方式不用为每一个引用类型的成员变量都调用一下自身的clone方法所以是比较推荐的方式

public class DeepCloneableTarget implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;

    private String cloneName;

    private String cloneClass;

    public DeepCloneableTarget(String cloneName, String cloneClass) {
        this.cloneName = cloneName;
        this.cloneClass = cloneClass;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class DeepProtoType implements Serializable,Cloneable {

    public String name;

    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }


    public Object deepClone(){
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前对象以对象流的方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType object = (DeepProtoType) ois.readObject();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {

        DeepProtoType d = new DeepProtoType();
        d.name = "kater";
        d.deepCloneableTarget = new DeepCloneableTarget("ke","le");

        DeepProtoType d1 = (DeepProtoType) d.deepClone();
        System.out.println("d.name=" + d.name + " d.deepCloneableTarget=" + d.deepCloneableTarget.hashCode());
        System.out.println("d1.name=" + d1.name + " d1.deepCloneableTarget=" + d1.deepCloneableTarget.hashCode());

    }
}

  (1)复制对象的所有基本数据类型的成员变量值

  (2)为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝

 

  原型模式:

  (1)创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率;

  (2)不用重新初始化对象,而是动态地获得对象运行时的状态

  (3)如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码

  (4)在实现深克隆的时候可能需要比较复杂的代码

  (5)需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了开放-封闭ocp原则

posted on 2024-03-27 21:26  homle  阅读(2)  评论(0编辑  收藏  举报