原型模式和深拷贝,浅拷贝

发布时间 2023-09-08 23:06:06作者: 长名06

原型模式

案例引入

克隆羊问题

有一只羊,姓名为tom,年龄为1,颜色为白色,编写程序创建和tom羊属性完全相同的羊。

传统方式解决

代码实现

public class Sheep {
    private String name;
    private int age;
    private String color;

    public Sheep() {
    }

    public Sheep(String name, int age, String color) {
        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;
    }
}
//测试
public class Client {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("tom", 1, "白色");
        Sheep sheep1 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        /**
        *  public String toString() {//Object类的toString()方法
        *      return getClass().getName() + "@" + Integer.toHexString(hashCode());//会输出全类名@符还有16进制的hashCode值
        *  }
        */
        System.out.println(sheep);//输出的对象的hashcode的值不相同,输出对象时,会默认的调用对象的toString()方法
        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);
    }
}
传统实现方式分析
  • 1.优点是好理解,简单易操作。
  • 2.缺点进行新对象创建时,总是需要重新获取原始对象的属性,如果创建的对象复杂时,效率很低。
  • 3.缺点,总是需要重新初始化对象(new操作),而不是动态的根据已有对象去创建,不灵活。
  • 4.改进思路,Java中Object类是所有类的基类,Object类提供了一个clone()方法,该方法可以将一个Java对象赋值一份,但是需要想使用这个方法的类必须要实现一个Cloneable接口,
    该接口才能复制,且具有复制的能力。

原型模式

基本介绍
  • 1.原型模式(Prototype Pattern)是指,用原型实例创建对象的种类,并且通过拷贝这些原型,创建新的对象。
  • 2.原型模式是一种设计型模式,允许一个对象再创建另一个可对象,无需知道创建的细节。
  • 3.工作原理是,通过将一个原型对象通过clone或者其他自己写的克隆方法,拷贝自身。
用原型模式实现案例
public class Sheep implements Cloneable{
    private String name;
    private int age;
    private String color;
    private String address = "蒙古羊";
    private Sheep friend;

    public Sheep() {
    }

    public Sheep(String name, int age, String color) {
        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;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Sheep getFriend() {
        return friend;
    }

    public void setFriend(Sheep friend) {
        this.friend = friend;
    }

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

    @Override
    protected Object clone() {
        Sheep sheep = null;
        try{
            sheep = (Sheep)super.clone();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return sheep;
    }
}

public class Client {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("tom", 1, "白色");
        sheep.setFriend(new Sheep("jack",1,"黑色"));

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

        System.out.println("sheep1=" + sheep1 + "sheep1.friend\n" + sheep1.getFriend().hashCode());//输出的hashCode值相同
        System.out.println("sheep2=" + sheep2 + "sheep2.friend\n" + sheep2.getFriend().hashCode());
    }
}

原型模式在Spring框架中的使用

//AbstractBeanFactory类doGetBean()的部分代码
else if (mbd.isPrototype()) {//判断当前bean是否是原型类型
   // It's a prototype -> create a new instance.
   Object prototypeInstance = null;
   try {
      beforePrototypeCreation(beanName);
      prototypeInstance = createBean(beanName, mbd, args);
   }
   finally {
      afterPrototypeCreation(beanName);
   }
   bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

深拷贝和浅拷贝

浅拷贝介绍
  • 1.浅拷贝,对于基本数据类型的属性,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
  • 2.对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组,某个类的对象等,浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制给新的对象。实际上两个对象的该成员变量都指向一个实例。在这种情况下,一个对象对于引用类型的属性的改变,就会影响到另一个对象的引用属性。
  • 3.前面克隆羊就是浅拷贝。
  • 4.浅拷贝是使用默认的clone方法来实现 sheep = (sheep) super.clone();
深拷贝介绍
  • 1.复制对象的所有属性,进行拷贝,就是说,基本数据类型拷贝成员变量值,引用数据类型的属性都申请存储空间,并复制每个引用类型属性所引用的对象,进行拷贝。也就是说对象进行深拷贝要对整个对象(包括对象的引用属性)进行拷贝。
  • 2.深拷贝实现方式,重写clone()和通过对象序列化和反序列化实现深拷贝(推荐)
    序列化,简单的说,就是将对象存储到磁盘。反序列化,将磁盘存储的对象读取到内存。
    代码演示
public class Money implements Serializable, Cloneable{
    private int account;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Person implements Serializable, Cloneable {
    private String name;
    private int age;
    private Money money;
    private static final long serialVersionID = 1L;

    public Person(String name, int age, Money money) {
        this.name = name;
        this.age = age;
        this.money = money;
    }

    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 Money getMoney() {
        return money;
    }

    public void setMoney(Money money) {
        this.money = money;
    }

    //1.重写clone方法完成深拷贝
    //这种方式存在问题,如果一个类中存在引用属性且没有为该属性复制
    //就会导致在进行克隆时会出现NullPointException,可以在clone前进行验证解决
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person person = null;
        //1.完成基本数据类型的clone
        person = (Person) super.clone();
        //2.对引用类型的属性,进行单独处理
        person.money = (Money) money.clone();
        return person;
    }

    //方式2 通过对象的序列化和反序列化实现
    public Object deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        Object object = null;
        try{
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//当前对象序列化到对象输出流中
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);//从输出流中反序列化到输入流中
            object = ois.readObject();//读取对象
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return object;
    }
}
//测试
public class TestDeepClone {
    public static void main(String[] args) throws CloneNotSupportedException {
        Money money = new Money();
        Person person = new Person("wind", 27, null);

        Person clone = (Person) person.clone();
//        Person clone = (Person) person.deepClone();
        System.out.println(person.getMoney().hashCode() + "-" + clone.getMoney().hashCode());
    }
}

注意事项和细节

  • 1.创建新的对象比较复杂,可以利用原型模式简化对象的创建过程,同时也能提高效率。
  • 2.不用再重新初始化对象,而是动态的根据对象的运行进行创建。
  • 3.如果原始对象发送变化(增加或减少属性),克隆对象的也不要发送变化,无需修改克隆的代码。
  • 4.实现深拷贝,需要比较复杂的代码。
  • 5.缺点,要为需要克隆的类,配一个克隆方法,这对新创建的类不难,但是对已有的类,需要修改源代码,违反了ocp。
    只是为了记录自己的学习历程,且本人水平有限,不对之处,请指正。