开发设计模式设计模式:03-原型模式
kikock1、克隆羊问题
现在有一只羊 tom,姓名为:tom,年龄为:1,颜色为:白色,请编写程序创建和 tom 羊属性完全相同的 10 只羊。
2、传统方式解决克隆羊问题
1)思路分析

2)代码演示
Sheep 羊类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class Sheep { private String name; private Integer age; private String color; public Sheep(final String name, final Integer age, final String color) { this.name = name; this.age = age; this.color = color; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(final Integer age) { this.age = age; } public String getColor() { return color; } public void setColor(final String color) { this.color = color; } @Override public String toString() { return "Sheep{" + "name='" + name + '\'' + ", age=" + age + ", color='" + color + '\'' + '}'; } }
|
Client 客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Client { public static void main(String[] args) { final Sheep sheep1 = new Sheep("tom", 1, "白色"); final Sheep sheep2 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor()); final Sheep sheep3 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor()); final Sheep sheep4 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor()); final Sheep sheep5 = new Sheep(sheep1.getName(), sheep1.getAge(), sheep1.getColor()); System.out.println(sheep1); System.out.println(sheep2); System.out.println(sheep3); System.out.println(sheep4); System.out.println(sheep5); } }
|
3、传统方式的优缺点
1)优点是比较好理解,简单易操作
2)在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率较低
3)总是需要重新初始化对象,而不是动态的获得对象运行时的状态,不够灵活
4)改进的思路分析
思路:Java 中 Object 类是所有类的根类,Object 类提供了一个 clone()方法,该方法可以将一个 Java 对象复制一份,但是需要实现 clone 的 Java 类必须要实现一个接口 Cloneable,该接口表示该类能够复制且具有复制的能力 -> 原型模式
4、原型模式
4.1 基本介绍
1)原型模式(Prototype 模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
2)原型模式是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节
3)工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝他们自己来实施创建,即 对象.clone()
4)形象的理解:孙大圣拔出猴毛,变出其他孙大圣
4.2 原理结构图-UML 类图

原理结构图说明:
1)Prototype:原型类,声明一个克隆自己的接口
2)ConcretePrototype:具体的原型类,实现一个克隆自己的操作
3)Client:让一个原型对象克隆自己,从而创建一个新的对象(属性一样)
4.3 原型模式解决克隆羊问题的应用实例
使用原型模式改进传统方式,让程序具有更高的效率和扩展性。
Sheep 羊类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class Sheep implements Cloneable { private String name; private Integer age; private String color; public Sheep(final String name, final Integer age, final String color) { this.name = name; this.age = age; this.color = color; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(final Integer age) { this.age = age; } public String getColor() { return color; } public void setColor(final String color) { this.color = color; } @Override public String toString() { return "Sheep[name=" + name + ",age=" + age + ",color=" + color + "]"; } @Override protected Object clone() { Sheep sheep = null; try { sheep = (Sheep) super.clone(); } catch (CloneNotSupportedException e) { System.out.println("error : " + e.getMessage()); } return sheep; } }
|
Client 客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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(); Sheep sheep4 = (Sheep) sheep.clone(); System.out.println("sheep1 : " + sheep1); System.out.println("sheep2 : " + sheep2); System.out.println("sheep3 : " + sheep3); System.out.println("sheep4 : " + sheep4); } }
|
5、原型模式在 Spring 框架中源码分析
1)Spring 中原型 bean 的创建,就是原型模式的应用
Monster 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class Monster { private Integer id = 10; private String nickname = "牛魔王"; private String skill = "芭蕉扇"; public Monster() { System.out.println("monster 创建"); } public Monster(final Integer id, final String nickname, final String skill) { this.id = id; this.nickname = nickname; this.skill = skill; } public Integer getId() { return id; } public void setId(final Integer id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(final String nickname) { this.nickname = nickname; } public String getSkill() { return skill; } public void setSkill(final String skill) { this.skill = skill; } @Override public String toString() { return "Monster{" + "id=" + id + ", nickname='" + nickname + '\'' + ", skill='" + skill + '\'' + '}'; } }
|
beans.xml
1 2 3 4 5 6 7 8 9 10 11
| <?xml version="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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="id01" class="com.wenze.design.prototype.springCoding.Monster" scope="prototype"/> </beans>
|
PrototypeTest 测试类
1 2 3 4 5 6 7 8
| public class PrototypeTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Object bean = applicationContext.getBean("id01"); System.out.println("bean: " + bean); } }
|
使用注解实现(类标记为)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| @Component @Scope("prototype") public class Monster { private Integer id = 10; private String nickname = "牛魔王"; private String skill = "芭蕉扇";
public Monster() { System.out.println("monster 创建"); } public Monster(final Integer id, final String nickname, final String skill) { this.id = id; this.nickname = nickname; this.skill = skill; } public Integer getId() { return id; } public void setId(final Integer id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(final String nickname) { this.nickname = nickname; } public String getSkill() { return skill; } public void setSkill(final String skill) { this.skill = skill; } @Override public String toString() { return "Monster{" + "id=" + id + ", nickname='" + nickname + '\'' + ", skill='" + skill + '\'' + '}'; } }
|
使用 Monster 类的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13
| ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Monster bean1 = context.getBean(Monster.class); bean1.setName("bean1");
Monster bean2 = context.getBean(Monster.class); bean2.setName("bean2");
System.out.println(bean1.getName()); System.out.println(bean2.getName());
|
6、深入讨论——浅拷贝和深拷贝
6.1 浅拷贝的介绍
1)对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
2)对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。
3)前面我们克隆羊就是浅拷贝
4)浅拷贝是使用默认的 clone() 方法来实现:sheep = (Sheep)super.clone();
6.2 深拷贝基本介绍
1)复制对象的所有基本数据类型的成员变量值
2)为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝。
3)深拷贝实现方式 1:重写 clone 方法来实现深拷贝
4)深拷贝实现方式 2:通过对象序列化实现深拷贝(推荐)
代码:
DeepCloneTarget
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.wenze.design.prototype.deepClone; import java.io.Serial; import java.io.Serializable;
public class DeepCloneableTarget implements Serializable, Cloneable { @Serial private static final long serialVersionUID = 1L; private String cloneName; private String cloneClass; public DeepCloneableTarget(final String cloneName, final String cloneClass) { this.cloneName = cloneName; this.cloneClass = cloneClass; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
|
DeepPrototype
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class DeepPrototype implements Serializable, Cloneable { public String name; public DeepCloneableTarget deepCloneableTarget; public DeepPrototype() { }
@Override protected Object clone() throws CloneNotSupportedException { Object deep = null; deep = super.clone(); DeepPrototype deepPrototype = (DeepPrototype) deep; deepPrototype.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone(); return deepPrototype; }
public DeepPrototype 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); return (DeepPrototype) ois.readObject(); } catch (Exception e) { System.out.println("error: " + e.getMessage()); return null; } finally { try { if (null != bos) { bos.close(); } if (null != oos) { oos.close(); } if (null != bis) { bis.close(); } if (null != ois) { ois.close(); } } catch (Exception e) { System.out.println("error: " + e.getMessage()); } } } }
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Client { public static void main(String[] args) throws Exception { final DeepPrototype deepPrototype = new DeepPrototype(); deepPrototype.name = "宋江"; deepPrototype.deepCloneableTarget = new DeepCloneableTarget("大牛", "大牛的类"); DeepPrototype deepPrototype1 = (DeepPrototype) deepPrototype.clone(); System.out.println("deepPrototype.name=" + deepPrototype.name + " deepPrototype.deepCloneableTarget=" + deepPrototype.deepCloneableTarget.hashCode()); System.out.println("deepPrototype1.name=" + deepPrototype1.name + " deepPrototype1.deepCloneableTarget=" + deepPrototype1.deepCloneableTarget.hashCode()); final DeepPrototype deepPrototype2 = deepPrototype.deepClone(); System.out.println("deepPrototype.name=" + deepPrototype.name + " deepPrototype.deepCloneableTarget=" + deepPrototype.deepCloneableTarget.hashCode()); System.out.println("deepPrototype2.name=" + deepPrototype2.name + " deepPrototype2.deepCloneableTarget=" + deepPrototype2.deepCloneableTarget.hashCode()); } }
|
7、原型模式的注意事项和细节
1)创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
2)不用重新初始化对象,而是动态的获得对象运行时状态
3)如果原始对象发生变化(增加或者减少属性),其他克隆对象的也会发生相应的变化,无需修改代码
4)在实现深克隆的时候可能需要比较复杂的代码
5)缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了 OCP 原则,这点请注意。
8、 总结
原型模式是一种创建型设计模式,它可以通过复制一个现有的对象来创建新的对象。
在Spring中,可以通过设置Bean的scope属性为“prototype”来实现原型模式。
原型模式的优点是可以减少对象的创建开销,提高性能,可以使对象的状态保持独立,避免相互影响,可以实现更灵活的对象创建机制。原型模式的缺点是增加了内存占用,可能导致对象之间的耦合。
原型模式通常用于创建轻量级对象,对于重量级对象,使用原型模式可能会导致性能问题。
原型模式可能会导致对象之间的耦合。如果两个对象相互引用,并且其中一个对象是原型scope的,则另一个对象也应该设置为prototype scope。