简介
1.原型模式(Prototype模式) 是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
2.原型模式是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节
3.工作原理是:通过将一个原型对象传给那个需要发动创建的对象,这个要发送创建的对象通过请求原型拷贝他们自己来实施创建 即 对象.clone()
4.形象的理解:孙大圣拔出猴毛,变出其他大圣.
克隆羊问题
现在有一只羊tom,姓名:tom,年龄为:1,颜色为:白色.请编写程序创建和tom 羊 属性完全相同的10只羊.
public class Sheep {
private String name;
private int age;
private String color;
/**
* @param name
* @param age
* @param color
*/
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + "]";
}
}
public class Cilent {
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());
Sheep sheep4 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep5 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep6 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep7 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep8 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep9 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep10 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
System.out.println(sheep);
System.out.println(sheep1);
System.out.println(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
//...........
}
}
传统方式的优缺点
1.优点是比较好理解,简单易操作
2.在创建新的对象的时候,总是需要重新获取原始对象的属性,如果创建的对象比较复杂,效率较低
3.总是需要重新初始化对象,而不是动态获取对象运行时的状态,不够灵活
4.改进的思路分析
思路 Java中的Object类是所有类的根类,Object类提供了一个 clone()方法,该方法可以将一个Java对象复制一份,但是需要实现clone的Java类必须要实现一个接口 Cloneable,该接口表示该类能够复制且具有复制的能力 ==>> 原型模式
增加 clone 的方法
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
/**
* @param name
* @param age
* @param color
*/
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + "]";
}
//克隆该实例,我们使用默认的 clone 方法
@Override
protected Object clone() {
Sheep sheep = null;
try {
sheep = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return sheep;
}
}
public class Cilent {
public static void main(String[] args) {
// 传统的方法
Sheep sheep = new Sheep("tom", 1, "白色");
Sheep clone1 = (Sheep) sheep.clone();
Sheep clone2 = (Sheep) sheep.clone();
Sheep clone3 = (Sheep) sheep.clone();
Sheep clone4 = (Sheep) sheep.clone();
Sheep clone5 = (Sheep) sheep.clone();
Sheep clone6 = (Sheep) sheep.clone();
System.out.println(clone1);
System.out.println(clone2);
System.out.println(clone3);
System.out.println(clone4);
System.out.println(clone5);
System.out.println(clone6);
}
}
打印结果
Sheep [name=tom, age=1, color=白色]
Sheep [name=tom, age=1, color=白色]
Sheep [name=tom, age=1, color=白色]
Sheep [name=tom, age=1, color=白色]
Sheep [name=tom, age=1, color=白色]
Sheep [name=tom, age=1, color=白色]
原型模式在Spring框架中的源码分析
这里我们的 scope="prototype" 即 原型模式来创建
<!-- 这里我们的 scope="prototype" 即 原型模式来创建 -->
<bean id="id01" class="cn.icanci.spring.bean.Monster" scope="prototype"/>
原型模式的深拷贝和浅拷贝
代码
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
private Sheep sheep;
/**
* @param name
* @param age
* @param color
*/
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return the sheep
*/
public Sheep getSheep() {
return sheep;
}
/**
* @param sheep the sheep to set
*/
public void setSheep(Sheep sheep) {
this.sheep = sheep;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + ", sheep=" + sheep + "]";
}
//克隆该实例,我们使用默认的 clone 方法
@Override
protected Object clone() {
Sheep sheep = null;
try {
sheep = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return sheep;
}
}
public class Cilent {
public static void main(String[] args) {
// 传统的方法
Sheep sheep = new Sheep("tom", 1, "白色");
sheep.setSheep(new Sheep("tom", 1, "白色"));
Sheep clone1 = (Sheep) sheep.clone();
Sheep clone2 = (Sheep) sheep.clone();
Sheep clone3 = (Sheep) sheep.clone();
Sheep clone4 = (Sheep) sheep.clone();
Sheep clone5 = (Sheep) sheep.clone();
Sheep clone6 = (Sheep) sheep.clone();
System.out.println(clone1 + " firendhashcode " + clone1.getSheep().hashCode() + " hashcode " + clone1.hashCode());
System.out.println(clone2 + " firendhashcode " + clone2.getSheep().hashCode() + " hashcode " + clone2.hashCode());
System.out.println(clone3 + " firendhashcode " + clone3.getSheep().hashCode() + " hashcode " + clone3.hashCode());
System.out.println(clone4 + " firendhashcode " + clone4.getSheep().hashCode() + " hashcode " + clone4.hashCode());
System.out.println(clone5 + " firendhashcode " + clone5.getSheep().hashCode() + " hashcode " + clone5.hashCode());
System.out.println(clone6 + " firendhashcode " + clone6.getSheep().hashCode() + " hashcode " + clone6.hashCode());
}
}
代码结果打印
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 1829164700
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 2018699554
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 1311053135
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 118352462
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 1550089733
Sheep [name=tom, age=1, color=白色, sheep=Sheep [name=tom, age=1, color=白色, sheep=null]] firendhashcode 366712642 hashcode 865113938
根据打印的结果我们会发现,sheep类里面的 成员变量sheep居然是引用,而不是一个新的对象 而发生这种状况的原因就是 对象的 浅拷贝
浅拷贝的介绍
1.对于数据类型是基本数据类型的成员变量,浅拷贝还会直接进行值传递,也就是将该属性值直接复制一份新的对象
2.对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组,某个类的对象等,那么浅拷贝会进行引用传递,也就是只传递该对象的引用值(内存地址)复制一份给新的对象,如上代码打印结果所示.因为实际上两个对象的该成员变量都指向同一个实例,在这种情况下,在每一个对象中修改该成员变量的值都会影响到另一个该还曾元变量值
3.前面的克隆羊就是浅拷贝
4.浅拷贝默认就是使用 默认的 clone方法来实现
sheep = (Sheep) super.clone();
深拷贝的介绍
1.复制对象所有的基本数据类型的成员变量值
2.为所有引用数据类型的成员变量申请内存空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达所有对象,也就是说深拷贝要对整个对象进行拷贝
3.深拷贝实现方式1:重写clone方法来实现深拷贝
4.深拷贝实现方式2: 通过对象序列化实现深拷贝
拷贝实现方式1:重写clone方法来实现深拷贝
public class DeepCloneableTarget implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String cloneName;
private String cloneClass;
public DeepCloneableTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
//因为该类的属性都是基本数据类型
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class DeepProtoType implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
public String name;
public DeepCloneableTarget cloneableTarget; // 引用数据类型
public DeepProtoType() {
super();
}
/**
* @param name
* @param cloneableTarget
*/
public DeepProtoType(String name, DeepCloneableTarget cloneableTarget) {
super();
this.name = name;
this.cloneableTarget = cloneableTarget;
}
// 完成深拷贝实现
// 方式1 使用克隆的方法
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
// 完成对金基本数据类型的克隆
deep = super.clone();
// 对引用数据类型进行单独处理
DeepProtoType deepTarget = (DeepProtoType) deep;
deepTarget.cloneableTarget = (DeepCloneableTarget) cloneableTarget.clone();
return deepTarget;
}
}
测试
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
DeepProtoType p = new DeepProtoType();
p.name="haxi";
p.cloneableTarget = new DeepCloneableTarget("xixi1", "呆子");
//方式1 完成深拷贝
DeepProtoType p1 = (DeepProtoType) p.clone();
System.out.println(p.name+" "+p.cloneableTarget.hashCode());
System.out.println(p1.name+" "+p1.cloneableTarget.hashCode());
}
}
测试打印结果
haxi 366712642
haxi 1829164700
//方式2 使用序列化完成深拷贝 推荐使用
public class DeepCloneableTarget implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String cloneName;
private String cloneClass;
public DeepCloneableTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
//因为该类的属性都是基本数据类型
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class DeepProtoType implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
public String name;
public DeepCloneableTarget cloneableTarget; // 引用数据类型
public DeepProtoType() {
super();
}
/**
* @param name
* @param cloneableTarget
*/
public DeepProtoType(String name, DeepCloneableTarget cloneableTarget) {
super();
this.name = name;
this.cloneableTarget = cloneableTarget;
}
// 完成深拷贝实现
// 方式1 使用克隆的方法
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
// 完成对金基本数据类型的克隆
deep = super.clone();
// 对引用数据类型进行单独处理
DeepProtoType deepTarget = (DeepProtoType) deep;
deepTarget.cloneableTarget = (DeepCloneableTarget) cloneableTarget.clone();
return deepTarget;
}
// 方式2 使用序列化完成深拷贝
public Object deeClone() {
// 创建流对象
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);
// 读取对象流
DeepProtoType copyObj = (DeepProtoType) ois.readObject();
return copyObj;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bos.close();
oos.close();
bis.close();
ois.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
return null;
}
}
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
DeepProtoType p = new DeepProtoType();
p.name="haxi";
p.cloneableTarget = new DeepCloneableTarget("xixi1", "呆子");
//方式1 完成深拷贝
// DeepProtoType p1 = (DeepProtoType) p.clone();
// System.out.println(p.name+" "+p.cloneableTarget.hashCode());
// System.out.println(p1.name+" "+p1.cloneableTarget.hashCode());
//方式2 完成深拷贝
DeepProtoType p1 = (DeepProtoType) p.deeClone();
System.out.println(p.name+" "+p.cloneableTarget.hashCode());
System.out.println(p1.name+" "+p1.cloneableTarget.hashCode());
}
}
打印结果
haxi 1118140819
haxi 558638686
原型设计模式的注意事项和细节
1.创建新的对象比较复杂的时候,可以利用原型模式简化对象的创建过程,同时也能提高效率
2.不用重新初始化对象,而是动态的获得对象运行时期的状态
3.如果原始对象发生变化(增加或者减少属性),其他克隆对象也会发生相应的编号,无需修改代码
4.在实现克隆的时候可能需要比较复杂的代码
5.缺点 需要为每一个类配置一个克隆方法.这对全新的类来说不是很困难,但是对已经有的类进行改造的时候,需要修改其源代码,违背了 ocp 原则,这点请同学们注意.