原型模式

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

原型UML:

举个栗子:
我们需要克隆羊,这里先不写接口或者抽象类,直接写具体类代表羊。

传统的克隆羊方式

会用 new Ship()方法。但在创建新对象时,总是需要重新获取原始对象的属性,如果创建得对象比较复杂时,效率较低。

因此有了原型模式

实现Java提供的一个接口Cloneable,接口表示该类能够复制且有复制的能力。
直接在Sheep类实现该接口,重写clone()方法。

代码实现:

public class Sheep implements Cloneable {
    private String name;
    private int age;
    private String color;
    private String address = "蒙古羊";
    public Sheep friend; //是对象, 克隆是会如何处理
    public Sheep(String name, int age, String color) {
        super();
        this.name = name;
        this.age = age;
        this.color = color;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }



    @Override
    public String toString() {
        return "Sheep [name=" + name + ", age=" + age + ", color=" + color + ", address=" + address + "]";
    }
    //克隆该实例,使用默认的clone方法来完成
    @Override
    protected Object clone()  {

        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
        // TODO Auto-generated method stub
        return sheep;
    }
}

public class Client {

    public static void main(String[] args) {
        System.out.println("原型模式完成对象的创建");
        // TODO Auto-generated method stub
        Sheep sheep = new Sheep("tom", 1, "白色");
        sheep.friend = new Sheep("jack", 2, "黑色");

        Sheep sheep2 = (Sheep)sheep.clone(); //克隆
        Sheep sheep3 = (Sheep)sheep.clone(); //克隆
        Sheep sheep4 = (Sheep)sheep.clone(); //克隆
        Sheep sheep5 = (Sheep)sheep.clone(); //克隆

        System.out.println(sheep2.hashCode());
        System.out.println(sheep3.hashCode());
        System.out.println(sheep4.hashCode());
        System.out.println(sheep5.hashCode());


        System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
        System.out.println("sheep3 =" + sheep3 + "sheep3.friend=" + sheep3.friend.hashCode());
        System.out.println("sheep4 =" + sheep4 + "sheep4.friend=" + sheep4.friend.hashCode());
        System.out.println("sheep5 =" + sheep5 + "sheep5.friend=" + sheep5.friend.hashCode());
    }
}

结果:
结果

可以发现,每个对象都是不同的,但是它们的引用却是指向了同一个。
这就是浅拷贝

浅拷贝

对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成
员变量值。
如果我们想要克隆的对象的引用都是单独的对象,彼此不受影响,就要进行深拷贝

深拷贝

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

实现方式:
(1)重写clone方法来实现深拷贝
(2)使用序列化来进行深拷贝

代码实现:

//被引用的对象
public class Master implements Serializable, Cloneable {

    String name;
    String age;

    Master(String name, String age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

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

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

public class Sheep implements Serializable, Cloneable {

    public String name;
    public Master master;

    //深拷贝 -方式1 使用clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {

        Object sheep = null;
        sheep = super.clone();

        Sheep sheep1 = (Sheep)sheep;
        //额外进行拷贝
        sheep1.master = (Master) master.clone();
        return sheep1;
    }

    //深拷贝 -方式2 通过对象的序列化
    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);
            Sheep copyObj = (Sheep)ois.readObject();
            return copyObj;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try{
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }catch (Exception e2){
                System.out.println(e2.getMessage());
            }
        }
    }
}

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {

        Sheep sheep = new Sheep();
        sheep.master = new Master("小明","4");

        Sheep sheep1 = (Sheep) sheep.clone();

        System.out.println("sheep----master:"+sheep.master.hashCode());
        System.out.println("sheep1----master:"+sheep1.master.hashCode());

        Sheep sheep2 = (Sheep) sheep.deepClone();
        System.out.println("sheep----master:"+sheep.master.hashCode());
        System.out.println("sheep2----master:"+sheep2.master.hashCode());

    }
}

结果:
图片说明
可以发现,克隆出来的引用的对象已经是独立的了!


注意:
缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则

应用:
Spring框架中原型bean的创建。

本文转载尚硅谷设计模式学习笔记,并做了些自己的补充。