原型模式(Prototype Pattern)

原型模式(Prototype Pattern)

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

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

案例一:传统方式

public class Sheep {
	private String name;
	private int age;
	private String color;
	//...省略get,set,toString,有参构造
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());
		//....
		
		System.out.println(sheep);
		System.out.println(sheep2);
		//...
	}
}

在这里插入图片描述

优点

  • 比较好理解, 简单易操作

缺点

  • 在创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率较低
  • 总是需要重新初始化对象,而不是动态地获得对象运行时的状态,不够灵活

案例二:原型模式

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

  • 原型模式(Prototype 模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
  • 原型模式是–种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节
  • 工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它
    clone对象实现Cloneable
public class Sheep implements Cloneable {
	private String name;
	private int age;
	private String color;
	private String address = "蒙古羊";
	public Sheep friend; //是对象, 克隆是会如何处理
	//...省略get,set,toString,有参构造
	//克隆该实例,使用默认的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) {
		System.out.println("原型模式完成对象的创建");
		// TODO Auto-generated method stub
		Sheep sheep = new Sheep("tom", 1, "白色");
		sheep.friend = new Sheep("jack", 2, "黑色");
		
		Sheep sheep2 = (Sheep)sheep.clone(); //克隆
		Sheep sheep3 = (Sheep)sheep.clone(); //克隆
		
		System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
		System.out.println("sheep3 =" + sheep3 + "sheep3.friend=" + sheep3.friend.hashCode());
	}
}

在这里插入图片描述

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

Spring中原型bean的创建,就是原型模式的应用

 <!-- 这里我们的 scope="prototype" 即 原型模式来创建 -->
 <!-- 这里我们的 scope="prototype" 即 原型模式来创建 -->
	<beans>
		<bean id="monster" class="com.jsxl.spring.bean.Monster" scope="prototype"/>
		<bean id="friend" class="com.jsxl.spring.bean.Friend" scope="prototype"/>
	</beans>
public class Monster {

	private Integer id = 10 ;
	private String nickname = "牛魔王";
	private String skill = "芭蕉扇";
	private Friend friend =new Friend(1,"孙悟空");
	//...省略get,set,toString,有参构造
}
public class Friend {
    private Integer;
    private String nickname;
	//...省略get,set,toString,有参构造
 <!-- 这里我们的 scope="prototype" 即 原型模式来创建 -->
	<beans>
		<bean id="monster" class="com.jsxl.spring.bean.Monster" scope="prototype"/>
		<bean id="friend" class="com.jsxl.spring.bean.Friend" scope="prototype"/>
	</beans>
public class ProtoType {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		// 获取monster[通过id获取monster]
		Monster monster = (Monster)applicationContext.getBean("monster");
		 monster.getFriend().hashCode();
		System.out.println("monster" + monster +"hashCode"+monster.getFriend().hashCode()); 
		Monster monster2 = (Monster)applicationContext.getBean("monster");
		System.out.println("monster2" + monster2+"hashCode"+monster2.getFriend().hashCode()); 
		System.out.println(monster == monster2); // false
	}
}

在这里插入图片描述
通过debug找到源码判断
在这里插入图片描述

// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								// Explicitly remove instance from singleton cache: It might have been put there
								// eagerly by the creation process, to allow for circular reference resolution.
								// Also remove any beans that received a temporary reference to the bean.
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

深入讨论浅拷贝和深拷贝

浅拷贝

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

浅拷贝是使用默认的clone()方法来实现

sheep = (Sheep) super.clone();

深拷贝

  • 复制对象的所有基本数据类型的成员变量值
  • 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象(包括对象的引用类型)进行拷贝
  • 深拷贝实现方式1:重写clone方法来实现深拷贝
  • 深拷贝实现方式2:通过对象序列化实现深拷贝(推荐)
    被引用对象继承Cloneable重新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;
	}
	//因为该类的属性,都是String , 因此我们这里使用默认的clone完成即可
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
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();
		
		// TODO Auto-generated method stub
		return deepProtoType;
	}
	
	//深拷贝 - 方式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) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		} finally {
			//关闭流
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}
		}
	}
}
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 完成深拷贝
		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());
	}
}

总结

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

在实现深克隆的时候可能需要比较复杂的代码

  • 缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则
  • 15
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
原型模式Prototype Pattern)是一种创建型设计模式,它允许通过复制现有对象来创建新对象,而无需通过显式的实例化过程。原型模式通过克隆(clone)已有对象来创建新对象,从而避免了使用传统的构造函数创建对象的开销。 在C++中,原型模式可以通过实现一个可克隆接口(通常称为原型接口)来实现。这个接口通常包含一个克隆方法,用于复制当前对象并返回一个新的副本。派生类可以实现这个接口来定义自己的克隆逻辑。 以下是原型模式的一般实现步骤: 1. 创建一个原型接口(或基类): ``` class Prototype { public: virtual Prototype* clone() const = 0; virtual void setAttributes(...) = 0; virtual void print() const = 0; }; ``` 2. 实现原型接口的具体类(或派生类): ``` class ConcretePrototype : public Prototype { private: // 在派生类中定义特定的属性 // ... public: Prototype* clone() const override { return new ConcretePrototype(*this); } void setAttributes(...) override { // 设置属性值 } void print() const override { // 打印属性值 } }; ``` 3. 在客户端代码中使用原型模式: ``` Prototype* original = new ConcretePrototype(); original->setAttributes(...); Prototype* clone = original->clone(); clone->print(); delete original; delete clone; ``` 通过使用原型模式,我们可以避免在每次创建对象时重复执行初始化的过程,提高了对象的创建效率。此外,原型模式还允许我们在运行时动态地添加或删除对象的属性,并通过克隆来创建新对象。 需要注意的是,在实现原型类时,需要确保所有成员变量都能正确地被拷贝(或克隆)。有时候可能需要自定义拷贝构造函数和赋值运算符来实现深拷贝,以避免浅拷贝带来的问题。 总结起来,原型模式通过克隆已有对象来创建新对象,提供了一种简单且灵活的对象创建方式。它适用于那些对象的创建过程比较复杂或开销较大的情况下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jsxllht

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值