设计模式学习——原型模式

在银河麒麟V10上部署Atlas 300i Duo:从固件到驱动的一站式踩坑笔记 日期:2025-09-09关键词:鲲鹏920、Atlas 300i Duo、银河麒麟V10、NPU、驱动、固件。 阅读详情

原型模式

基本介绍

  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原则。
别再傻傻分不清了!Anaconda和Miniconda到底选哪个?附保姆级安装与镜像源配置(Windows/Mac) 本文详细解析了Anaconda和Miniconda的核心差异,包括体积、预装内容、系统资源占用等关键维度,并提供了针对不同需求的决策框架。附有Windows和Mac双平台的详细安装与配置指南,帮助用户根据实际需求选择最适合的conda工具,提升开发效率。 阅读详情

相关推荐

国产数据库安装部署说明

国产数据库安装部署说明

weixin_38203586的博客 909

Spring设置bean的原型模式

在默认情况下, Spring应用上下文中所有bean都是作为以单例 ( singleton)的形式创建的。也就是说,不管给定的一个bean被注入 到其他bean多少次,每次所注入的都是同一个实例。 在大多数情况下,单例bean是很理想的方案。初始化和垃圾回收对象 实例所带来的成本只留给一些小规模任务,在这些任务中,让对象保 持无状态并且在应用中反复重用这些对象可能并不合理。 有时候,可能会

feng905001561的专栏 1万+

【Musescore 】开源打谱软件 快速入门笔记

前两天做了个西贝柳斯的打谱软件学习笔记,反正都是初学,今天再来学习一款同类软件,比较之后确定一款深入学习。 西贝柳斯的学习笔记在此:https://blog.youkuaiyun.com/yuetaope/article/details/120020342 西贝柳斯是商业收费软件,要么花钱,要么盗版,如果您觉得这两者都不大好,那么推荐您试试Musescore。 Musescore是一款非常优秀的开源的打谱软件,生态繁荣。“开源”和“生态”是码农业的术语,我用正常人类的语言简单解释一下。 开源就是开放程序源代码,对码农

专注于医院数据分析技术与系统开发的创作与分享。 1万+

设计模式--原型模式--Spring框架中使用原型模式创建新的bean实例

1 bean的scope:有一种prototype,容器在接受到该类型对象请求的时候,都会重新生成一个新的对象实例给请求方,该标志内部实现就是实用来了原型模式,完成对象的生成。源码:/** * Actually create the specified bean. Pre-creation processing has already happened * at this point, e...

qfzhangwei的专栏 2381

声音事件检测metric:PSDS

这项工作为多声道声音事件检测(SED)系统的性能评估定义了一个新的框架,它克服了传统的collar-based事件决定、事件F-cores和事件错误率的限制。拟议的框架引入了对事件检测的定义,该定义对标签的主观性更为稳健。它还采用了多声道接收器操作特性(ROC)曲线,以提供比F1分数更全面的系统性能洞察力,并建议将这些曲线简化为单一的多声道声音检测分数(PSDS),这允许系统独立于操作点(OPs)进行比较。所提出的方法还能更好地了解不同声音类别的数据偏差和分类稳定性。

Maestro_T的博客 2730

yolov5 onnx推理时报错[ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Unexpected input data type.

yolov5 onnxruntime 推理报错

zjulkw的博客 1223

设计模式 原型模式 与 Spring 原型模式源码解析(包含Bean的创建过程)

原创 疯狂的狮子Li发表于辽宁。

竹林幽深 492

H3C无线控制器AC与第三方认证系统集成实现企业级Portal短信认证方案

本文详细阐述了如何将H3C无线控制器(AC)与第三方认证系统集成,构建企业级Portal短信认证方案。该方案通过手机号作为临时凭证,实现了访客网络的实名追溯、权限控制与专业体验。文章深入解析了方案原理、H3C AC的关键配置步骤、第三方系统对接要点及短信网关选型避坑指南,为企业提升网络安全管理与访客服务质量提供了完整、可行的实战指导。

a3b4c5的博客 195

手写简易版Spring框架(八):单例、原型Bean以及FactoryBean的实现和使用

手写简易版Spring框架(八):单例、原型Bean以及FactoryBean的实现和使用

zhang_qing_yun的博客 636

qcc514x-qcc304x调试笔记

qcc514x-qcc304x调试笔记-1-QCC514x系列 qcc514x-qcc304x调试笔记-2-开发环境搭建 qcc514x-qcc304x调试笔记-3-如何修改蓝牙名称 qcc514x-qcc304x调试笔记-4-如何修改蓝牙地址 qcc514x-qcc304x调试笔记-5-如何区分左右耳 qcc514x-qcc304x调试笔记-6-PIO相关操作 ...

leezs的博客 1244

vue3+ts+elementui-plus二次封装树形表格实现不同层级展开收起的功能

我只定义了三层数据,就只演示展开了三层,还可以多层,自己设置即可。

蜗牛~~ 2602

Spring设计模式——原型模式

原型模式(Prototype Pattern),是指原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。

胖胖爱吃肉~的博客 470

为分析表明卡诺电池技术(或热泵式储电技术)-是目前最佳的储能技术!!!-2021年

卡诺电池(Carnot Battery)是一种基于热力学循环的储能技术,其核心原理是通过热力循环将电能转化为热能存储,并在需要时将热能重新转换为电能输出。这种技术得名于热力学中的卡诺循环原理,由法国工程师卡诺于1824年提出。

qq_15963745的博客 656

设计模式 - 学习笔记 - 原型模式Prototype Pattern

设计模式 - 学习笔记 - 原型模式Prototype Pattern学习总结动机 Motivation应用场景UML代码示例1. 实现 Cloneable 接口: 浅拷贝2. 实现自己定义接口 Prototype: 浅拷贝实现 Cloneable 接口,序列化/反序列化: 浅深贝参考资料 学习总结 对象创建模式。解耦:你别new你直接用interface接就行了,要啥你直接叫我。 原型的特点就是自我复制。Java中的Cloneable接口和它的clone()方法想必都接触过吧。 动机 Motivati

灵台方寸山斜月三星洞 557

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

认真学习设计模式之原型模式(Prototype Pattern)

# 【1】概述 原型模式(Prototype 模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象。 原型模式是一种`创建型`设计模式,允许一个对象再创建另外一个可定制的对象,无需知道如何创建的细节 工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建,即`对象.clone()`。 形象的理解:孙大圣拔出猴毛, 变出其它孙大圣 ## **① UML类图** ![在这里插入图片描述](https://img-blog

小小默:进无止境 909

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

设计模式学习笔记九:原型模式(Prototype Pattern)

设计模式学习笔记九:原型模式(Prototype Pattern)   1.概述     意图:我们将已经存在的对象作为原型,用户可以通过复制这些原型创建新的对象。     使用场合:当一个系统应该独立于产品的创建、构造和表示时,可以使用原型模式。在原型模式中,产品的创建和初始化再类的Clone方法中完成。在使用是,我们可以用一些列原型对象来代替生成相应对象的工厂对象,并且可

AlbenXie的博客 372

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

学习设计模式《八》——原型模式

 原型模式的本质是【克隆生成对象】

提供C#相关开发 、云计算、运维测试、网络安全相关技术分享与服务,有意向可联系。 1557

java设计模式学习之【原型模式】

这篇教程不仅提供了原型模式的理论基础,还通过具体的Java代码示例展示了如何实现和应用这种模式。简单理解,通俗易懂

qq_33129875的博客 1679

设计模式之原型模式学习

什么是原型模式 原型模式是一种创建型模式,它采取复制原型对象的方法来创建对象的实例。使用原型模式创建的实例,具有与原型一样的数据。 原型模式的特点 1、由原型对象自身创建目标对象。也就是说,对象创建这一动作发自原型对象本身。 2、目标对象是原型对象的一个克隆。也就是说,通过原型模式创建的对象,不仅仅与原型对象具有相同的结构,还与原型对象具有相同的值。 3、根据对象克隆深度层次的不同,有浅度克隆...

Arrset的博客 260

深入JAVA框架学习23种设计模式-原型模式

快速失败机制的实现是通过在集合的内部维护一个计数器(modCount),每次修改集合时都会增加计数器的值。接下来这段代码是我们今天的重点第一个判断显然是对单例模式bean对象的获取,最主要我们来看第二个,即对原型模式bean对象获取方法,首先将prototypeInstance赋为空值null,定义了一个Object对象prototypeInstance,注意这两个对象并不是一个对象,它们所处的作用域不同即位于不同的{}内的代码块,prototypeInstance在上个代码块中时String[]对象。

weixin_61854715的博客 1170

Android开发学习笔记之设计模式——原型模式&建造者模式

文章目录Android开发学习笔记之设计模式——原型模式&建造者模式原型模式概述应用场景优缺点实现建造者模式概述应用场景优缺点实现 Android开发学习笔记之设计模式——原型模式&建造者模式 原型模式 概述 在开发过程中,我们经常会遇到这样的问题,如果我们想要创建一个非常复杂的对象,那我们可能需要进行相当多的处理,尤其是数据类,通常都存在很多成员变量,而其中很多变量还是需要通过I/O操作获取的,此时创建一个新的对象的成本就显得很高了。此时,我们或许会想,如果存在一种方法可以复制原有的对象就

qq_36425800的博客 504

设计模式学习之原型模式

UML结构类图的常用画法 简单工厂 设计模式学习之外观模式 设计模式学习之适配器模式 设计模式学习之单例模式 设计模式学习之工厂方法模式 设计模式学习之生成器模式 Demo传送门 案例:订单处理系统 订单分为个人订单和公司订单,客户对订单的要求如下:当订单的预定产品数量超过500时,需要将订单拆成两份订单来保存,如果拆分后的子订单数量依然超过500,那就继续拆分,直到每一份订单的数量都小于50...

weixin_34409741的博客 105

学习设计模式之原型模式

文章目录一、定义二、问题背景三、违背设计模式的设计实现四、问题改进五、总结 一、定义 二、问题背景 三、违背设计模式的设计实现 四、问题改进 五、总结

南淮北安的博客 589

设计模式学习-原型模式

《西游记》相信大家都并不陌生,关于他(或它)拔毛变小猴的故事几乎人人皆知,孙悟空可以用猴毛根据自己的形象,复制(又称“克隆”或“拷贝”)出很多跟自己长得一模一样的“身外身”来。在设计模式中也存在一个类似的模式,可以通过一个原型对象克隆出多个一模一样的对象,该模式称之为原型模式。 在使用原型模式时,我们需要首先创建一个原型对象,再通过复制这个原型对象来创建更多同类型的对象。试想,如果连孙悟空的模样都不知道,怎么拔毛变小猴子呢?原型模式的定义如下: 原型模式(PrototypePattern):使用原型..

小猴子的博客 233

Java23种设计模式之原型模式的学习

源码链接(Gitee码云):https://gitee.com/oldou/javadesignpatterns 这里有我整理好的Java23种设计模式的源码以及博客教程,博客教程中介绍了Java23种设计的模式的各种实现方式以及应用场景,非常适用于学习以及提高我们的设计思维,如果对大家有所帮助,请记得star一下给予作者一定的精神支持,你的star是我写出更好的博客的动力,谢谢大家。 原型模式(prototype) 介绍 原型模式(Prototype Pattern)是用于创建重复的对象,同时又能..

weixin_43246215的博客 3294
上一篇: 设计模式学习——工厂模式
下一篇: 设计模式学习——建造者模式
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值