Java设计模式——原型模式(ProtoType)

一、引言

23种设计模式大概分为三大类:

5种(创建型模式):工厂方法模式、抽象工厂模式、单例模式、原型模式、建造者模式。

7种(结构型模式):适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

11种(行为型模式):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

行为型又可以通过类与类之间的关系进行划分 :
在这里插入图片描述

原型模式基本介绍:

(1)、原型模式(Prototype模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象

(2)、原型模式:是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象, 无需知道如何创建的细节

(3)、工作原理:是通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即 对象.clone()

二、案列分析

1、克隆羊问题

现在有一只羊Tom,姓名为:tom,年龄为:1,颜色为:白色。 请编写程序创建和tom羊属性完全相同的5只羊。

2、传统方式解决克隆羊问题
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 + "]";
	}
}

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());
				
		System.out.println(sheep);
		System.out.println(sheep2);
		System.out.println(sheep3);
		System.out.println(sheep4);
		System.out.println(sheep5);
	}
}

// 运行结果
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=白色]

上面的代码,应该没人看不懂吧~~~~~

3、传统方式解决克隆羊问题的优缺点

(1)、优点是比较好理解,简单易操作。

(2)、在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率较低(想象一下,如果这只羊有20几个属性,难道每个属性,都要调用get方法吗?)

(3)、总是需要重新初始化对象,而不是动态地获得对象运行时的状态, 不够灵活

(4)、改进的思路

Java中Object类是所有类的根类,Object类提供了一个clone()方法,该方法可以将一个Java对象复制一份,但是需要实现clone的Java类必须要实现一个接口Cloneable,该接口表示该类能够复制且具有复制的能力 => 原型模式

三、使用原型模式解决克隆羊问题

原型模式解决克隆羊问题,让程序具有更高的效率和扩展性。在使用原型模式之前,先介绍一下浅拷贝和深拷贝

1、浅拷贝和深拷贝
(1)、浅拷贝的介绍

1)、对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。

2)、 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。

3)、浅拷贝是使用默认的 clone()方法来实现。
在这里插入图片描述

public class Sheep implements Cloneable {
	private String name;
	private int age;
	private String color;
	private String address = "内蒙古";
	public Sheep friend;	// 有个朋友,引用类型

	public Sheep(String name, int age, String color) {
		super();
		this.name = name;
		this.age = age;
		this.color = color;
	}

	// set、get、tostring方法忽略
	
	// 实现Clonealbe接口,并重写其中的clone方法
	@Override
	protected Object clone() {

		Sheep sheep = null;
		try {
			sheep = (Sheep) super.clone();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return sheep;
	}

}

public class Client {

	public static void main(String[] args) {
		Sheep sheep = new Sheep("tom", 1, "白色");

		sheep.friend = new Sheep("jack", 2, "黄色");

		// 直接调用clone方法,就可以创建出一个新对象,这个要注意引用类型
		Sheep sheep2 = (Sheep) sheep.clone(); 
		Sheep sheep3 = (Sheep) sheep.clone(); 
		Sheep sheep4 = (Sheep) sheep.clone(); 
		Sheep sheep5 = (Sheep) sheep.clone(); 

		System.out.println("sheep2 =" + sheep2 + ",sheep2.friend=" + sheep2.friend.hashCode());
		System.out.println("sheep3 =" + sheep3 + ",sheep3.friend=" + sheep3.friend.hashCode());
		System.out.println("sheep4 =" + sheep4 + ",sheep4.friend=" + sheep4.friend.hashCode());
		System.out.println("sheep5 =" + sheep5 + ",sheep5.friend=" + sheep5.friend.hashCode());
	}

}

// 运行结果
sheep2 =Sheep [name=tom, age=1, color=白色, address=内蒙古],sheep2.friend=1632905274
sheep3 =Sheep [name=tom, age=1, color=白色, address=内蒙古],sheep3.friend=1632905274
sheep4 =Sheep [name=tom, age=1, color=白色, address=内蒙古],sheep4.friend=1632905274
sheep5 =Sheep [name=tom, age=1, color=白色, address=内蒙古],sheep5.friend=1632905274

说明:
可以发现应用类型为同一个对象,即引用类型并没有重写创建。
使用原型模式的浅拷贝之后,即使Sheep类的属性发生改变,对Client的调用依旧没有影响。

(2)、深拷贝基本介绍

1)、复制对象的所有基本数据类型的成员变量值

2)、 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝
3)、 深拷贝实现方式:

第一种:重写clone方法来实现深拷贝;
第二种:通过对象序列化实现深拷贝(推荐);

在这里插入图片描述

// 要拷贝的目标对象,实现Serializable、Cloneable接口
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 {

	public String name;
	public DeepCloneableTarget deepCloneableTarget;

	public DeepProtoType() {
		super();
	}

	// 方式一: clone方式实现深拷贝
	@Override
	protected Object clone() throws CloneNotSupportedException {
		Object deep = null;
		deep = super.clone();
		DeepProtoType deepProtoType = (DeepProtoType) deep;
		deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
		return deepProtoType;
	}

	// 方式二:序列化方式实现深拷贝
	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) {
				// TODO: handle exception
				System.out.println(e2.getMessage());
			}
		}
	}
}

public class Client {

	public static void main(String[] args) throws Exception {
		DeepProtoType p = new DeepProtoType();
		p.name = "Tom";
		p.deepCloneableTarget = new DeepCloneableTarget("friend", "深拷贝");

		// 方式一
		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());
		System.out.println("------------------------------");

		// 方式二
		DeepProtoType p3 = (DeepProtoType) p.deepClone();
		System.out.println("p.name=" + p.name + ",p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
		System.out.println("p3.name=" + p.name + ",p3.deepCloneableTarget=" + p3.deepCloneableTarget.hashCode());

	}

}


// 运行结果
p.name=Tom,p.deepCloneableTarget=1088333500
p2.name=Tom,p2.deepCloneableTarget=1502913001
------------------------------
p.name=Tom,p.deepCloneableTarget=1088333500
p3.name=Tom,p3.deepCloneableTarget=1659213513

说明:
可以看出,深拷贝之后得到对象的hashcode都不一样,说明引用对象都不一样。

四、原型模式小结

优点:

1、创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
2、不用重新初始化对象,而是动态地获得对象运行时的状态
3、如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码
4、在实现深克隆的时候可能需要比较复杂的代码

缺点:

1、需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则。

五、原型模式在Spring框架中源码分析

Spring中原型bean的创建,就是原型模式的应用。在Spring的配置文件中,下面的代码,应该不陌生:

<bean id="tom" class="com.scorpios.designpattern.prototype.Sheep" scope="prototype"/>

上面的代码是创建一个Bean,指定scope为prototype,表示以原型模式来创建该Bean。

发布了123 篇原创文章 · 获赞 230 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/zxd1435513775/article/details/96638442
今日推荐