前言

  1. 原型模式(Prototype模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
  2. 原型模式是一种创建型设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节。
  3. 工作原理:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即 对象.clone()
  4. 形象的理解:孙大圣拔出猴毛,变出其他孙大圣

原型模式类图实例

  1. Prototype:原型类,声明一个克隆自己的接口
  2. ConcretePrototype:具体的原型类,实现一个克隆自己的操作。
  3. Client:让一个原型对象克隆自己,从而创建一个新的对象(属性一样)

原型模式java代码实例

Sheep类实现Cloneable接口重写clone方法

 public class Sheep implements Cloneable{

    private String name;
private int age;
private String color; public Sheep(String name, int age, String color) {
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;
}
}

Client类测试创建多个Sheep的实例,查看是否状态一致。

public class Client {
public static void main(String[] args) {
System.out.println("原型模式完成对象的创建");
Sheep sheep=new Sheep("tom",1,"白色");
Sheep sheep2=(Sheep)sheep.clone();
Sheep sheep3=(Sheep)sheep.clone();
Sheep sheep4=(Sheep)sheep.clone();
System.out.println("sheep2: "+sheep2);
System.out.println("sheep3: "+sheep3);
System.out.println("sheep4: "+sheep4); }
}

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

  1. Spring中原型Bean的创建,就是原型模型的应用
  2. 代码分析

    ProtoType类的测试用例
public class ProtoType {

    public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Object bean = applicationContext.getBean("id01");
System.out.println("bean" + bean); Object bean2 = applicationContext.getBean("id01"); System.out.println(bean==bean2); }
}

beans.xml配置文件

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 这里我们的scope="prototype" 即 原型模式 -->
<bean id="id01" class="com.spring.bean.Monster" scope="prototype"></bean>
</beans>

追踪 applicationContext.getBean(“id01”):进入AbstractApplicationContext类的getBean方法

//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//--------------------------------------------------------------------- @Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}

追踪getBeanFactory():进入AbstractRefreshableApplicationContext类的getBeanFactory()方法

@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}

追踪getBean():进入AbstractBeanFactory类的getBean()方法

@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}

追踪doGetBean():进入doGetBean()方法

通过if (mbd.isSingleton()) 和else if (mbd.isPrototype())判断scope的作用域,

通过createBean()创建一个原型模型,返回一个bean。

/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);
Object bean; // Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
} // Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
} if (!typeCheckOnly) {
markBeanAsCreated(beanName);
} try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
} // Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
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);
} else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
} // Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}

浅拷贝

  1. 对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
  2. 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组,某个类型的对象等,那么浅拷贝会进行引用传递,也就是只是该成员变量的引用值(内存地址)复制一份给新的对象,因为实际上两个对象的该成员变量都指向同一个实例,在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。
  3. 克隆羊的案例就是浅拷贝
  4. 浅拷贝是使用默认的clone()方法来实现sheep=(Sheep)super。clone();

浅拷贝代码实例:

在原有的Sheep类基础上添加 public Sheep friend;

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) {
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;
}
}

编写Client的测试用例,打印sheep.friend的hashCode值,观察它是否产生了新的对象。

public class Client {
public static void main(String[] args) {
System.out.println("原型模式完成对象的创建");
Sheep sheep = new Sheep("tom", 1, "白色");
sheep.friend=new Sheep("jack",2,"黑色");
Sheep sheep2 = (Sheep) sheep.clone();
Sheep sheep3 = (Sheep) sheep.clone();
Sheep sheep4 = (Sheep) sheep.clone();
System.out.println("sheep2: " + sheep2+"sheep.friend2="+sheep2.friend.hashCode());
System.out.println("sheep3: " + sheep3+"sheep.friend3="+sheep3.friend.hashCode());
System.out.println("sheep4: " + sheep4+"sheep.friend4="+sheep4.friend.hashCode());
}
}

基本介绍

  1. 复制对象的所有基本数据类型的成员变量值
  2. 为所有的引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,知道该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝
  3. 深拷贝实现方式一:重写clone方法来实现深拷贝
  4. 深拷贝实现方式二:通过对象序列化来实现深拷贝

深拷贝代码实例:

方式一:重写clone方法

DeepCloneableTarget类

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();
}
}

DeepProtoType类

public class DeepProtoType implements Serializable, Cloneable {

    public String name;
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 deep;
}
}

测试用例:Client

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="+p2.name+"p.deepCloneableTarget="+p2.deepCloneableTarget.hashCode()); }
}

方式二:通过对象序列化来实现深拷贝(推荐使用)

DeepCloneableTarget类

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();
}
}

DeepProtoType 类

public class DeepProtoType implements Serializable, Cloneable {

    public String name;
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) {
e2.printStackTrace();
}
}
}
}

Client 测试用例

public class Client {
public static void main(String[] args) throws Exception {
DeepProtoType p = new DeepProtoType();
p.name = "宋江";
p.deepCloneableTarget = new DeepCloneableTarget("大牛", "小牛的"); //方式2 完成深拷贝
DeepProtoType p3=(DeepProtoType) p.deepClone(); System.out.println("p.name=" + p.name + "p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
System.out.println("p3.name=" + p3.name + "p.deepCloneableTarget=" + p3.deepCloneableTarget.hashCode()); }
}

原型模式的注意事项和细节

  1. 创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率
  2. 不用重新初始化对象,而是动态地获得对象运行时的状态
  3. 如果院士对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码。
  4. 在实现深克隆的时候可能需要比较复杂的代码
  5. 缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了ocp原则。

最后

感谢你看到这里,看完有什么的不懂的可以在评论区问我,觉得文章对你有帮助的话记得给我点个赞,每天都会分享java相关技术文章或行业资讯,欢迎大家关注和转发文章!

深度分析:java设计模式中的原型模式,看完就没有说不懂的的更多相关文章

  1. java设计模式-----5、原型模式

    原型(Prototype)模式是一种对象创建型模式,他采取复制原型对象的方法来创建对象的实例.使用原型模式创建的实例,具有与原型一样的数据. 原型模式的特点: 1.由原型对象自身创建目标对象.也就是说 ...

  2. 《JAVA设计模式》之原型模式(Prototype)

    在阎宏博士的<JAVA与模式>一书中开头是这样描述原型(Prototype)模式的: 原型模式属于对象的创建模式.通过给出一个原型对象来指明所有创建的对象的类型,然后用复制这个原型对象的办 ...

  3. 重学 Java 设计模式:实战原型模式

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 老板你加钱我的代码能飞 程序员这份工作里有两种人:一类是热爱喜欢的.一类是仅当成工作 ...

  4. Java设计模式5:原型模式

    原型模式 原型模式属于对象的创建模式,通过给出一个原型对象来指明所有创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象,这就是原型模式的用意. 原型模式结构 原型模式要求对象实现一个 ...

  5. Java设计模式:Prototype(原型)模式

    概念定义 使用原型实例指定待创建对象的种类,并通过拷贝该原型来创建新的对象.Prototype模式允许一个原型对象克隆(复制)出多个与其相同的对象,而无需知道任何如何创建的细节. 应用场景 对象的创建 ...

  6. 【java设计模式】-06原型模式

    原型模式简述 定义: 使用原型实例指定待创建对象的类型,并且通过复制这个原型来创建新的对象 ,也就是通过复制现有对象实例产生新的对象,也就是所谓的"克隆" 实现方式: 1.实现Cl ...

  7. JAVA设计模式之【原型模式】

    1.案例一 学生复制 package Prototype; /** * Created by Jim on 2016/10/1. */ public class Student implements ...

  8. Java设计模式学习记录-原型模式

    前言 最近一直在面试,也没时间写博客了,感觉已经积攒了好多知识想要记录下来了,因为在面试中遇到的没答出来的问题,这就是自己不足的地方,然后就要去学习这部分内容,虽然说自己不足的地方学习了,但是没有应用 ...

  9. 重学 Java 设计模式:实战代理模式「模拟mybatis-spring中定义DAO接口,使用代理类方式操作数据库原理实现场景」

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 难以跨越的瓶颈期,把你拿捏滴死死的! 编程开发学习过程中遇到的瓶颈期,往往是由于看不 ...

随机推荐

  1. MySQL备份和恢复[3]-mysqldump备份工具

    mysqldump 概述 逻辑备份工具: mysqldump, mydumper, phpMyAdmin Schema和数据存储在一起.巨大的SQL语句.单个巨大的备份文件 mysqldump:是My ...

  2. 使用ModelForm校验数据唯一性

    在设计模型类的时候,将指定字段设置unique=true属性,可以保证该字段在数据库中的唯一性. 使用ModelForm可以将指定模型类快速生成表单元素.在提交数据后,使用is_valid()校验时, ...

  3. 子父类存在同名成员时super的使用条件

    1.子父类存在同名成员时,子类中默认访问子类的成员,可通过super指定访问父类的成员,格式:super.xx  (注:xx是成员名): 2.创建子类对象时,默认会调用父类的无参构造方法,可通过sup ...

  4. Cisco思科模拟器交换机划分VLAN 入门详解 - 精简归纳

    Cisco思科模拟器交换机划分VLAN 入门详解 - 精简归纳 JERRY_Z. ~ 2020 / 10 / 24 转载请注明出处!️ 附: 交流方式: ️ ️ ️ QQ: 1846334075 We ...

  5. JVM内存管理和垃圾回收

    无论对于Java程序员还是大数据研发人员,JVM是必须掌握的技能之一.既是面试中经常问的问题,也是在实际业务中对程序进行调优.排查类似于内存溢出.栈溢出.内存泄漏等问题的关键.笔者将按下图分多篇文章详 ...

  6. Distcp 跨集群同步

    date: 2020-10-09 17:45:00 updated: 2020-10-10 17:45:00 Distcp 跨集群同步 1. 使用方法及原理 hadoop distcp srcPath ...

  7. C2. Power Transmission (Hard Edition) 解析(思維、幾何)

    Codeforce 1163 C2. Power Transmission (Hard Edition) 解析(思維.幾何) 今天我們來看看CF1163C2 題目連結 題目 給一堆點,每兩個點會造成一 ...

  8. DTU是怎么与PLC连接通信的

    数据采集是生产制造中最实际最频繁的需求,不管智能设备制造发展到何种程度它都是工业4.0的先决条件,也在数字化工厂当中,工人更多地是处理异常情况,调整设备.但数据采集一直是困扰着所有制造工厂的传统痛点, ...

  9. 【译】Rust,无畏并发

    原文链接:https://dev.to/imaculate3/fearless-concurrency-5fk8 > 原文标题:That's so Rusty! Fearless concurr ...

  10. Android Studio的第一次经历

    第一个简单APP的制作是从xml开始的,通过在java新建一个empty  activity,并在layout里找到对应的xml文件进行编写.每编写一个xml就要事先新建 一个对应的empty  ac ...