设计模式学习笔记 - 原型模式
一、克隆羊问题
克隆羊问题:现在有一只羊,姓名为 tom、年龄为1岁、颜色为白色,创建与tom羊的属性完全相同的10只羊。
二、使用传统的方式实现
-
类图:
-
实现代码:
package com.etc.design.prototype;
public class Sheep {
private String name;
private int age;
private String color;
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + "]";
}
}
package com.etc.design.prototype;
public class Client {
public static void main(String[] args) {
//传统的方法
Sheep sheep = new Sheep("tom", 1, "白色");
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("tom", 1, "白色");
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(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
System.out.println(sheep5);
System.out.println(sheep6);
System.out.println(sheep7);
System.out.println(sheep8);
System.out.println(sheep9);
System.out.println(sheep10);
}
}
传统方式的优缺点:
(1)优点:比较好理解,简单易操作。
(2)缺点:在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率较低。总是需要重新初始化对象,而不是动态地获得对象运行时的状态,不够灵活。
(3)改进的思路分析:Java中Object类是所有类的根类,Object类提供了一个clone()方法,该方法可以将一个Java对象复制一份,但是需要实现clone()方法的Java类必须要实现一个接口Cloneable,该接口表示该类能够复制且具有复制的能力。这种方式使用了原型模式。
三、原型模式介绍
原型模式(Prototype模式):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式是用于创建许多重复的对象,同时又能保证性能。
原型模式是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节。
工作原理是通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即对象.clone()
。
- 类图:
四、使用原型模式的方式实现
使用原型模式改进传统方式,让程序具有更高的效率和扩展性。
- 实现代码:
package com.etc.design.prototype.improve;
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
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 (Exception e) {
System.out.println(e.getMessage());
}
return sheep;
}
}
package com.etc.design.prototype.improve;
public class Client {
public static void main(String[] args) {
Sheep sheep = new Sheep("tom", 1, "白色");
Sheep sheep2 = (Sheep)sheep.clone(); //克隆
Sheep sheep3 = (Sheep)sheep.clone(); //克隆
Sheep sheep4 = (Sheep)sheep.clone(); //克隆
Sheep sheep5 = (Sheep)sheep.clone(); //克隆
Sheep sheep6 = (Sheep)sheep.clone(); //克隆
Sheep sheep7 = (Sheep)sheep.clone(); //克隆
Sheep sheep8 = (Sheep)sheep.clone(); //克隆
Sheep sheep9 = (Sheep)sheep.clone(); //克隆
Sheep sheep10 = (Sheep)sheep.clone(); //克隆
System.out.println(sheep);
System.out.println(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
System.out.println(sheep5);
System.out.println(sheep6);
System.out.println(sheep7);
System.out.println(sheep8);
System.out.println(sheep9);
System.out.println(sheep10);
}
}
五、原型模式在Spring框架中源码分析
Spring中原型bean的创建,就是原型模式的应用。选择原型模式创建对象实例,每次调用getBean方法获取的对象实例都是不同的。
package com.atguigu.spring.bean;
/**
* 注释
* @author Administrator
*
*/
public class Monster {
private Integer id = 10 ;
private String nickname = "牛魔王";
private String skill = "芭蕉扇";
public Monster() {
System.out.println("monster 创建..");
}
public Monster(Integer id, String nickname, String skill) {
this.id = id;
this.nickname = nickname;
this.skill = skill;
}
public Monster( String nickname, String skill,Integer id) {
this.id = id;
this.nickname = nickname;
this.skill = skill;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
@Override
public String toString() {
return "Monster [id=" + id + ", nickname=" + nickname + ", skill="
+ skill + "]";
}
}
package com.atguigu.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ProtoType {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// 获取monster(通过id获取monster)
Object bean = applicationContext.getBean("id01");
System.out.println("bean" + bean); // 输出"牛魔王" .....
Object bean2 = applicationContext.getBean("id01");
System.out.println("bean2" + bean2); // 输出"牛魔王" .....
System.out.println(bean == bean2); // false, 表示bean和bean2不是一个对象
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 这里的scope="prototype",即使用原型模式来创建 -->
<bean id="id01" class="com.atguigu.spring.bean.Monster" scope="prototype"/>
</beans>
- Spring源码中选择原型模式(配置文件beans.xml中设置scope=“prototype”)创建实例的代码:
.........
// 单例模式
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 原型模式
else if (mbd.isPrototype()) {
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
........
六、浅拷贝和深拷贝
1、浅拷贝
对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。
浅拷贝是使用默认的clone()方法来实现。
package com.etc.design.prototype.shallowcopy;
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) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
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 (Exception e) {
System.out.println(e.getMessage());
}
return sheep;
}
}
package com.etc.design.prototype.shallowcopy;
public class Client {
public static void main(String[] args) {
Sheep sheep = new Sheep("tom", 1, "白色");
sheep.friend = new Sheep("jack", 2, "黑色");
System.out.println("sheep =" + sheep + "sheep.friend=" + sheep.friend.hashCode());
Sheep sheep2 = (Sheep)sheep.clone(); //克隆
System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
}
}
2、深拷贝
复制对象的所有基本数据类型的成员变量值,为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝,要对整个对象(包括对象的引用类型)进行拷贝。
深拷贝实现方式有:
(1)使用两层浅拷贝实现(重写clone方法)。
(2)通过对象序列化实现。
- 深拷贝-实现方式1:使用两层浅拷贝(重写clone方法)实现深拷贝。
package com.etc.design.prototype.deepcopy;
import java.io.Serializable;
public class DeepProtoType implements Serializable, Cloneable{
public String name; // String属性
public DeepCloneableTarget deepCloneableTarget; // 引用类型
public DeepProtoType() {
super();
}
// 深拷贝-方式1:使用两层浅拷贝实现(重写clone方法)
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
// 这里完成对基本数据类型(属性)和String的克隆
deep = super.clone();
// 对引用类型的属性,进行单独处理
DeepProtoType deepProtoType = (DeepProtoType)deep;
deepProtoType.deepCloneableTarget = (DeepCloneableTarget)deepCloneableTarget.clone();
return deepProtoType;
}
}
package com.etc.design.prototype.deepcopy;
import java.io.Serializable;
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;
}
// 因为该类的属性,都是String类型, 因此这里使用默认的clone完成即可
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.etc.design.prototype.deepcopy;
public class Client {
public static void main(String[] args) throws Exception {
DeepProtoType p = new DeepProtoType();
p.name = "小明";
p.deepCloneableTarget = new DeepCloneableTarget("大牛", "小牛");
// 使用方式1完成深拷贝
DeepProtoType p2 = (DeepProtoType) p.clone();
System.out.println("p.name=" + p.name + ",p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
System.out.println("p2.name=" + p.name + ",p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
}
}
- 深拷贝-实现方式2:通过对象序列化实现深拷贝(推荐)。
package com.etc.design.prototype.deepcopy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class DeepProtoType implements Serializable, Cloneable{
public String name; // String属性
public DeepCloneableTarget deepCloneableTarget; // 引用类型
public DeepProtoType() {
super();
}
// 深拷贝-方式2:通过对象的序列化实现(推荐)
public Object 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);
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 (Exception e2) {
System.out.println(e2.getMessage());
}
}
}
}
package com.etc.design.prototype.deepcopy;
import java.io.Serializable;
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;
}
// 因为该类的属性,都是String类型, 因此这里使用默认的clone完成即可
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.etc.design.prototype.deepcopy;
public class Client {
public static void main(String[] args) throws Exception {
DeepProtoType p = new DeepProtoType();
p.name = "小明";
p.deepCloneableTarget = new DeepCloneableTarget("大牛", "小牛");
// 使用方式2完成深拷贝
DeepProtoType p2 = (DeepProtoType) p.deepClone();
System.out.println("p.name=" + p.name + ",p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
System.out.println("p2.name=" + p.name + ",p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
}
}
七、原型模式的注意事项和细节
(1)创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率。
(2)不用重新初始化对象,而是动态地获得对象运行时的状态。
(3)如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码。
(4)在实现深克隆的时候可能需要比较复杂的代码。
(5)缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则。