由克隆羊问题引出原型模式:
现在有一只羊tom,姓名为: tom, 年龄为:1,颜色为:白色,请编写程序创建和tom羊属性完全相同的10只羊。
传统方式
直接new一个羊的对象,拿过来使用即可,后面向"克隆这只羊",直接把姓名、年龄属性全部复用。
羊Sheep
- public class Sheep {
- private String name;
- private int age;
- private String color;
-
- public Sheep(String name, int age, String color) {
- this.name = name;
- this.age = age;
- this.color = color;
- }
-
- //get,set,toString省略
- }
客户端Client
- 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());
- }
- }
问题分析
改进的思路分析
Java 中 Object 类是所有类的根类,Object 类提供了一个 clone()方法,该方法可以将一个 Java 对象复制一份,但是需要实现 clone 的 Java 类必须要实现一个接口 Cloneable,该接口表示该类能够复制且具有复制的能力 => 原型模式
1)原型模式(Prototype 模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
2)原型模式是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节
3)工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即对象.clone()
设计方案
实现Cloneable接口,重写clone()方法
羊Sheep
- public class Sheep implements Cloneable{
- private String name;
- private int age;
- private String color;
-
- public Sheep(String name, int age, String color) {
- this.name = name;
- this.age = age;
- this.color = color;
- }
-
- //省略get set toString方法
-
- //克隆该实例,使用默认的clone方法来完成
- @Override
- protected Object clone() {
- Sheep sheep =null;
- try {
- sheep= (Sheep) super.clone();
- } catch (CloneNotSupportedException e) {
- System.out.println(e.getMessage());
- }
- return sheep;
- }
- }
客户端Client
- public class Client {
- public static void main(String[] args) {
- Sheep sheep = new Sheep("tom", 1, "白");
- Sheep sheep1 =(Sheep) sheep.clone();
- Sheep sheep2 =(Sheep) sheep.clone();
- Sheep sheep3 =(Sheep) sheep.clone();
- }
- }
1)对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
2)对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值
3)浅拷贝是使用默认的 clone()方法来实现
就用刚才克隆羊案例来看,这只羊有个好朋友
在原来的基础上添加一个Sheep类型的属性;
- public class Sheep implements Cloneable{
- private String name;
- private int age;
- private String color;
- public Sheep friend;
-
- public Sheep(String name, int age, String color) {
- this.name = name;
- this.age = age;
- this.color = color;
- }
-
- //省略get set toString方法
-
- @Override
- protected Object clone() {
- Sheep sheep =null;
- try {
- sheep= (Sheep) super.clone();
- } catch (CloneNotSupportedException e) {
- System.out.println(e.getMessage());
- }
- return sheep;
- }
- }
客户端Client
- public class Client {
- public static void main(String[] args) {
- Sheep sheep = new Sheep("tom", 1, "白");
- sheep.friend = new Sheep("jack",2,"蓝");
-
- Sheep sheep1 =(Sheep) sheep.clone();
- Sheep sheep2 =(Sheep) sheep.clone();
- Sheep sheep3 =(Sheep) sheep.clone();
-
- System.out.println(sheep + "\n--->sheep friend hashCode:" + sheep.friend.hashCode());
- System.out.println(sheep1 + "\n--->sheep1 friend hashCode:" + sheep1.friend.hashCode());
- System.out.println(sheep2 + "\n--->sheep2 friend hashCode:" + sheep2.friend.hashCode());
- System.out.println(sheep3 + "\n--->sheep3 friend hashCode:" + sheep3.friend.hashCode());
- }
- }
结果:注意克隆羊的好朋友没有变;
- Sheep{name='tom', age=1, color='白', friend=Sheep{name='jack', age=2, color='蓝', friend=null}}
- --->sheep friend hashCode:692404036
- Sheep{name='tom', age=1, color='白', friend=Sheep{name='jack', age=2, color='蓝', friend=null}}
- --->sheep1 friend hashCode:692404036
- Sheep{name='tom', age=1, color='白', friend=Sheep{name='jack', age=2, color='蓝', friend=null}}
- --->sheep2 friend hashCode:692404036
- Sheep{name='tom', age=1, color='白', friend=Sheep{name='jack', age=2, color='蓝', friend=null}}
- --->sheep3 friend hashCode:692404036
1)复制对象的所有基本数据类型的成员变量值
2)为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝
3)深拷贝实现方式 1:重写clone方法来实现深拷贝
4)深拷贝实现方式 2:通过对象序列化实现深拷贝(推荐)
User类,作为另一个类的引用类型属性
- public class User implements Cloneable{
-
- public String name;
- public String address;
-
- public User(String name, String address) {
- this.name = name;
- this.address = address;
- }
-
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- //toString省略
- }
拷贝对象,引用User类
- public class DeepProtoType implements Cloneable {
-
- public String nation;
- public User user;
-
- //深拷贝 ;重写clone方法实现;
- @Override
- protected Object clone() throws CloneNotSupportedException {
- Object deep = null;
-
- //对String类型 进行处理;
- deep = super.clone();
- DeepProtoType deepProtoType =(DeepProtoType) deep;
-
- //对引用类型处理;
- deepProtoType.user= (User) user.clone();
-
- return deepProtoType;
- }
-
- //省略toString
-
- }
克隆测试
- public class Client {
- public static void main(String[] args) throws CloneNotSupportedException {
- DeepProtoType deepProtoType = new DeepProtoType();
- deepProtoType.nation="中国";
- deepProtoType.user=new User("小卤蛋","陕西省");
-
- //方式一;
- DeepProtoType dp1 = (DeepProtoType) deepProtoType.clone();
- DeepProtoType dp2 = (DeepProtoType) deepProtoType.clone();
-
- //原来的;
- System.out.println(deepProtoType);
- System.out.println("user属性原哈希值"+deepProtoType.user.hashCode());
-
- //查看克隆后的;
- System.out.println("========克隆后;第一个========");
- System.out.println(dp1);
- System.out.println("user属性 哈希值"+dp1.user.hashCode());
-
- System.out.println("========克隆后;第二个========");
- System.out.println(dp2);
- System.out.println("user属性 哈希值"+dp2.user.hashCode());
- }
- }
结果:
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性原哈希值692404036
- ========克隆后;第一个========
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性 哈希值1554874502
- ========克隆后;第二个========
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性 哈希值1846274136
User类
- public class User implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- public String name;
- public String address;
-
- public User(String name, String address) {
- this.name = name;
- this.address = address;
- }
-
- //省略toString
- }
拷贝对象,引用User类
- public class DeepProtoType implements Serializable {
-
- private static final long serialVersionUID = 2L;
-
- public String nation;
- //引用类型
- public User user;
-
- //方式二
- public Object deepClone(){
- //创建流对象
- ByteArrayOutputStream bos = null;
- ByteArrayInputStream bis =null;
- ObjectOutputStream oos=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 copyObj=(DeepProtoType)ois.readObject();
-
- return copyObj;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }finally {
- try {
- bos.close();
- oos.close();
- bis.close();
- ois.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- //省略toString
- }
克隆测试
- public class Client {
- public static void main(String[] args) throws CloneNotSupportedException {
- DeepProtoType deepProtoType = new DeepProtoType();
- deepProtoType.nation="中国";
- deepProtoType.user=new User("小卤蛋","陕西省");
-
- //方式一;
- DeepProtoType dp1 = (DeepProtoType) deepProtoType.deepClone();
- DeepProtoType dp2 = (DeepProtoType) deepProtoType.deepClone();
-
- //原来的;
- System.out.println(deepProtoType);
- System.out.println("user属性原哈希值"+deepProtoType.user.hashCode());
-
- //查看克隆后的;
- System.out.println("========克隆后;第一个========");
- System.out.println(dp1);
- System.out.println("user属性 哈希值"+dp1.user.hashCode());
-
- System.out.println("========克隆后;第二个========");
- System.out.println(dp2);
- System.out.println("user属性 哈希值"+dp2.user.hashCode());
-
- }
- }
结果:
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性原哈希值1725154839
- ========克隆后;第一个========
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性 哈希值883049899
- ========克隆后;第二个========
- DeepProtoType{nation='中国', user=User{name='小卤蛋', address='陕西省'}}
- user属性 哈希值2093176254
Spring 中原型 bean 的创建,就是原型模式的应用
写个实体类
- public class Book {
- private String name;
- private int id;
- private String author;
-
- //省略get,set,toString方法
- }
bean.xml文件
作用类型切换为scope=“prototype”
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <bean id="book" class="prototype_03.Book" scope="prototype">
- <property name="author" value="卤蛋"/>
- <property name="id" value="2"/>
- <property name="name" value="java"/>
- bean>
- beans>
测试
- public class Test {
- public static void main(String[] args) {
- ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("prototype_03/bean1.xml");
- Book book1 = (Book)applicationContext.getBean("book");
- Book book2 = (Book)applicationContext.getBean("book");
- System.out.println(book1);
- System.out.println(book2);
- System.out.println(book1 == book2);
- }
- }
运行结果
Book{name='java', id=2, auuthor='卤蛋'}
Book{name='java', id=2, auuthor='卤蛋'}
false
debug调试
1)创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
2)不用重新初始化对象,而是动态地获得对象运行时的状态
3)如果原始对象发生变化(增加或者减少属性),其它克隆对象也会发生相应的变化,无需修改代码
4)在实现深克隆的时候可能需要比较复杂的代码
缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了 ocp 原则,这点需要注意。