ToB企服应用市场:ToB评测及商务社交产业平台

标题: 原型模式和深拷贝,浅拷贝 [打印本页]

作者: tsx81428    时间: 2023-9-9 00:19
标题: 原型模式和深拷贝,浅拷贝
原型模式

案例引入

克隆羊问题

有一只羊,姓名为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. 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. 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. }
复制代码
注意事项和细节


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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4