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

打印 上一主题 下一主题

主题 868|帖子 868|积分 2606

原型模式

案例引入

克隆羊问题

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

代码实现
  1. public class Sheep {
  2.     private String name;
  3.     private int age;
  4.     private String color;
  5.     public Sheep() {
  6.     }
  7.     public Sheep(String name, int age, String color) {
  8.         this.name = name;
  9.         this.age = age;
  10.         this.color = color;
  11.     }
  12.     public String getName() {
  13.         return name;
  14.     }
  15.     public void setName(String name) {
  16.         this.name = name;
  17.     }
  18.     public int getAge() {
  19.         return age;
  20.     }
  21.     public void setAge(int age) {
  22.         this.age = age;
  23.     }
  24.     public String getColor() {
  25.         return color;
  26.     }
  27.     public void setColor(String color) {
  28.         this.color = color;
  29.     }
  30. }
  31. //测试
  32. public class Client {
  33.     public static void main(String[] args) {
  34.         Sheep sheep = new Sheep("tom", 1, "白色");
  35.         Sheep sheep1 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
  36.         Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
  37.         Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
  38.         /**
  39.         *  public String toString() {//Object类的toString()方法
  40.         *      return getClass().getName() + "@" + Integer.toHexString(hashCode());//会输出全类名@符还有16进制的hashCode值
  41.         *  }
  42.         */
  43.         System.out.println(sheep);//输出的对象的hashcode的值不相同,输出对象时,会默认的调用对象的toString()方法
  44.         System.out.println(sheep1);
  45.         System.out.println(sheep2);
  46.         System.out.println(sheep3);
  47.     }
  48. }
复制代码
传统实现方式分析


  • 1.优点是好理解,简单易操作。
  • 2.缺点进行新对象创建时,总是需要重新获取原始对象的属性,如果创建的对象复杂时,效率很低。
  • 3.缺点,总是需要重新初始化对象(new操作),而不是动态的根据已有对象去创建,不灵活。
  • 4.改进思路,Java中Object类是所有类的基类,Object类提供了一个clone()方法,该方法可以将一个Java对象赋值一份,但是需要想使用这个方法的类必须要实现一个Cloneable接口,
    该接口才能复制,且具有复制的能力。
原型模式

基本介绍


  • 1.原型模式(Prototype Pattern)是指,用原型实例创建对象的种类,并且通过拷贝这些原型,创建新的对象。
  • 2.原型模式是一种设计型模式,允许一个对象再创建另一个可对象,无需知道创建的细节。
  • 3.工作原理是,通过将一个原型对象通过clone或者其他自己写的克隆方法,拷贝自身。
用原型模式实现案例
  1. public class Sheep implements Cloneable{
  2.     private String name;
  3.     private int age;
  4.     private String color;
  5.     private String address = "蒙古羊";
  6.     private Sheep friend;
  7.     public Sheep() {
  8.     }
  9.     public Sheep(String name, int age, String color) {
  10.         this.name = name;
  11.         this.age = age;
  12.         this.color = color;
  13.     }
  14.     public String getName() {
  15.         return name;
  16.     }
  17.     public void setName(String name) {
  18.         this.name = name;
  19.     }
  20.     public int getAge() {
  21.         return age;
  22.     }
  23.     public void setAge(int age) {
  24.         this.age = age;
  25.     }
  26.     public String getColor() {
  27.         return color;
  28.     }
  29.     public void setColor(String color) {
  30.         this.color = color;
  31.     }
  32.     public String getAddress() {
  33.         return address;
  34.     }
  35.     public void setAddress(String address) {
  36.         this.address = address;
  37.     }
  38.     public Sheep getFriend() {
  39.         return friend;
  40.     }
  41.     public void setFriend(Sheep friend) {
  42.         this.friend = friend;
  43.     }
  44.     @Override
  45.     public String toString() {
  46.         return "Sheep{" +
  47.                 "name='" + name + '\'' +
  48.                 ", age=" + age +
  49.                 ", color='" + color + '\'' +
  50.                 ", address='" + address + '\'' +
  51.                 ", friend=" + friend +
  52.                 '}';
  53.     }
  54.     @Override
  55.     protected Object clone() {
  56.         Sheep sheep = null;
  57.         try{
  58.             sheep = (Sheep)super.clone();
  59.         }catch (Exception e){
  60.             System.out.println(e.getMessage());
  61.         }
  62.         return sheep;
  63.     }
  64. }
  65. public class Client {
  66.     public static void main(String[] args) {
  67.         Sheep sheep = new Sheep("tom", 1, "白色");
  68.         sheep.setFriend(new Sheep("jack",1,"黑色"));
  69.         Sheep sheep1 = (Sheep)sheep.clone();
  70.         Sheep sheep2 = (Sheep)sheep.clone();
  71.         System.out.println("sheep1=" + sheep1 + "sheep1.friend\n" + sheep1.getFriend().hashCode());//输出的hashCode值相同
  72.         System.out.println("sheep2=" + sheep2 + "sheep2.friend\n" + sheep2.getFriend().hashCode());
  73.     }
  74. }
复制代码
原型模式在Spring框架中的使用
  1. //AbstractBeanFactory类doGetBean()的部分代码
  2. else if (mbd.isPrototype()) {//判断当前bean是否是原型类型
  3.    // It's a prototype -> create a new instance.
  4.    Object prototypeInstance = null;
  5.    try {
  6.       beforePrototypeCreation(beanName);
  7.       prototypeInstance = createBean(beanName, mbd, args);
  8.    }
  9.    finally {
  10.       afterPrototypeCreation(beanName);
  11.    }
  12.    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  13. }
复制代码
深拷贝和浅拷贝

浅拷贝介绍


  • 1.浅拷贝,对于基本数据类型的属性,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
  • 2.对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组,某个类的对象等,浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制给新的对象。实际上两个对象的该成员变量都指向一个实例。在这种情况下,一个对象对于引用类型的属性的改变,就会影响到另一个对象的引用属性。
  • 3.前面克隆羊就是浅拷贝。
  • 4.浅拷贝是使用默认的clone方法来实现 sheep = (sheep) super.clone();
深拷贝介绍


  • 1.复制对象的所有属性,进行拷贝,就是说,基本数据类型拷贝成员变量值,引用数据类型的属性都申请存储空间,并复制每个引用类型属性所引用的对象,进行拷贝。也就是说对象进行深拷贝要对整个对象(包括对象的引用属性)进行拷贝。
  • 2.深拷贝实现方式,重写clone()和通过对象序列化和反序列化实现深拷贝(推荐)
    序列化,简单的说,就是将对象存储到磁盘。反序列化,将磁盘存储的对象读取到内存。
    代码演示
  1. public class Money implements Serializable, Cloneable{
  2.     private int account;
  3.     @Override
  4.     protected Object clone() throws CloneNotSupportedException {
  5.         return super.clone();
  6.     }
  7. }
  8. public class Person implements Serializable, Cloneable {
  9.     private String name;
  10.     private int age;
  11.     private Money money;
  12.     private static final long serialVersionID = 1L;
  13.     public Person(String name, int age, Money money) {
  14.         this.name = name;
  15.         this.age = age;
  16.         this.money = money;
  17.     }
  18.     public String getName() {
  19.         return name;
  20.     }
  21.     public void setName(String name) {
  22.         this.name = name;
  23.     }
  24.     public int getAge() {
  25.         return age;
  26.     }
  27.     public void setAge(int age) {
  28.         this.age = age;
  29.     }
  30.     public Money getMoney() {
  31.         return money;
  32.     }
  33.     public void setMoney(Money money) {
  34.         this.money = money;
  35.     }
  36.     //1.重写clone方法完成深拷贝
  37.     //这种方式存在问题,如果一个类中存在引用属性且没有为该属性复制
  38.     //就会导致在进行克隆时会出现NullPointException,可以在clone前进行验证解决
  39.     @Override
  40.     protected Object clone() throws CloneNotSupportedException {
  41.         Person person = null;
  42.         //1.完成基本数据类型的clone
  43.         person = (Person) super.clone();
  44.         //2.对引用类型的属性,进行单独处理
  45.         person.money = (Money) money.clone();
  46.         return person;
  47.     }
  48.     //方式2 通过对象的序列化和反序列化实现
  49.     public Object deepClone() {
  50.         ByteArrayOutputStream bos = null;
  51.         ObjectOutputStream oos = null;
  52.         ByteArrayInputStream bis = null;
  53.         ObjectInputStream ois = null;
  54.         Object object = null;
  55.         try{
  56.             bos = new ByteArrayOutputStream();
  57.             oos = new ObjectOutputStream(bos);
  58.             oos.writeObject(this);//当前对象序列化到对象输出流中
  59.             bis = new ByteArrayInputStream(bos.toByteArray());
  60.             ois = new ObjectInputStream(bis);//从输出流中反序列化到输入流中
  61.             object = ois.readObject();//读取对象
  62.         }catch (IOException | ClassNotFoundException e){
  63.             e.printStackTrace();
  64.         }finally {
  65.             try {
  66.                 bos.close();
  67.                 oos.close();
  68.                 bis.close();
  69.                 ois.close();
  70.             } catch (IOException e) {
  71.                 e.printStackTrace();
  72.             }
  73.         }
  74.         return object;
  75.     }
  76. }
  77. //测试
  78. public class TestDeepClone {
  79.     public static void main(String[] args) throws CloneNotSupportedException {
  80.         Money money = new Money();
  81.         Person person = new Person("wind", 27, null);
  82.         Person clone = (Person) person.clone();
  83. //        Person clone = (Person) person.deepClone();
  84.         System.out.println(person.getMoney().hashCode() + "-" + clone.getMoney().hashCode());
  85.     }
  86. }
复制代码
注意事项和细节


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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81428

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表