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

RT-DETR改进策略【卷积层】| CGblock 内容引导网络 利用不同层次信息,提高多类别分类能力 (含二次创新) 本文记录的是利用中的模块优化的目标检测网络模型。通过局部特征提取器、周围环境提取器、联合特征提取器和全局环境提取器来提取局部特征、周围环境和全局环境信息,充分利用不同层次的信息。本文将其应用到中,并进行二次创新,使网络能够更好的处理多类别目标的分类能力。CGNet: A Light-Weight Context Guided Network for Semantic Segmentation1️⃣ 首先通过局部特征提取器floc(∗)floc(*)floc(∗)和周围环境提取器fsur(∗)f_{sur } 阅读详情

原型模式

基本介绍

  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原则。
Vue2 - 详细实现解析Markdown内容生成侧边栏Toc目录索引,识别文章内容根据大标题/小标题自动生成多级文章目录,点击目录导航时跳转到文章内容对应的锚点位置带过渡动画,滑过锚点时高亮对应标题 vue2,nuxt2,Markdown,目录,文章目录锚点,滚动高亮导航文字,根据页面滚动高亮显示目录的侧边栏,自动提取标题生成右侧目录,vuemarkdown解析并生成目录,滚动页面的时候文章目录跟着选中效果,侧边栏滚动跟随页面,右边目录固定,左边内容可以滚动并且与左边目录联动,实现监听滚动,锚点定位,文章目录滚动跟随高亮,右边菜单点击目录滚动到对应标题,报错,渲染失败,文章内容,读取#标题符号,自动生成一个目录树,自动生成Toc目录,博客内容生成目录索引,资讯文章,生成锚点目录树TOC,详细示例代码教 阅读详情

相关推荐

Spyglass实战指南:跨时钟域同步方案深度解析

本文深度解析了Spyglass在跨时钟域同步方案验证中的实战应用。通过真实案例阐述了亚稳态的危害,并详细介绍了从基础的两级同步器到复杂的异步FIFO与握手协议等八大同步方案,以及如何利用Spyglass进行有效配置、检查与问题排查,为提升芯片设计可靠性提供系统性的避坑指南。

weixin_29219189的博客 844

Spring设置bean的原型模式

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

feng905001561的专栏 1万+

别再为电路自激发愁了:手把手教你用吸波材料搞定微波腔体谐振(附HFSS仿真设置)

本文详细解析了微波腔体谐振问题的工程解决方案,重点介绍了吸波材料的选型、安装工艺及HFSS仿真设置。通过实际案例和计算工具,帮助射频工程师有效抑制腔体自激,提升系统稳定性。特别适用于35GHz毫米波雷达等高频电路设计场景。

weixin_42662293的博客 391

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

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

qfzhangwei的专栏 2381

大模型部署之二--vllm+docker部署

本文介绍了在openEuler系统上快速本地部署Qwen3-8B、DeepSeek-R1、Qwen2.5deng 大模型的完整流程。通过modelscope管理模型,采用vllm+docker模式实现部署。主要步骤包括:1)安装conda环境;2)配置docker;3)下载模型;4)编写docker compose配置文件;5)启动服务。特别针对2卡4090服务器提供了参数配置建议,并给出常用命令和参考资料。文档还提示不同系统和平台可能存在差异,为开发者提供了本地部署大型语言模型的实用指南。

weixin_39279863的博客 1137

手把手用瑞萨E1仿真器调试RH850 CAN通信:从报文收发到底层寄存器监控

本文详细介绍了使用瑞萨E1仿真器调试RH850 CAN通信的全过程,包括硬件连接、CS+开发环境配置、CAN控制器寄存器解析以及双通道网关实战开发。通过实战案例和错误诊断技巧,帮助开发者快速掌握RH850F1L的RS-CAN控制器应用,提升车载网络开发效率。

weixin_30919429的博客 168

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

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

竹林幽深 492

QGIS:安装Deepness插件+应用

简单的描述了deepness的安装应用历程,重点是记录博主本次遇到的坑

fengyi157的博客 2360

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

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

zhang_qing_yun的博客 637

【华为OD机试真题 新系统】1043、魔法咒语组合 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS)

【华为OD机试真题 新系统】1043、魔法咒语组合 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS) 华为od机试,华为od机试真题,华为od机试E卷,华为odE卷,华为od机试真题E卷,华为OD,华为OD机试,华为OD机试真题,华为od机考,华为od机试D卷,华为od机试真题D卷,华为od手撕代码,华为od,华为od机试C卷,华为od e卷,华为2026e卷,od机试,2026E卷,华为OD机试E卷,什么是华为od,华为od介绍,全面了解华为od,2026华为od,如何备战华为od

KJ.JK 291

喷涂机器人系列编程:ABB IRB 5500_(9).常见故障诊断与排除

ABB IRB 5500 喷涂机器人在实际应用中可能会遇到各种故障,但通过系统的诊断和排除方法,可以确保生产线的连续运行。定期维护和保养是预防故障的重要手段,而操作培训和规范则能有效减少人为因素引起的故障。希望本节内容能帮助操作和维护人员提高故障诊断和排除的效率,确保喷涂机器人的稳定运行。如果您有任何疑问或需要进一步的帮助,请联系 ABB 客户服务中心。

zhubeibei168的博客 1046

Spring设计模式——原型模式

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

胖胖爱吃肉~的博客 470

【深度学习驱动流体力学】完整配置安装 OpenFOAM 及其所需的ThirdParty与QT5工具

针对以上文件及文件目录介绍其功能特性:Allclean:这是一个脚本或命令,通常用于清理(即删除)所有编译生成的临时文件和目标文件。执行后,可以将编译过程中生成的中间文件和已编译的程序删除,以便重新开始编译或者清理空间。Allwmake:这是一个脚本或命令,用于编译并安装ThirdParty-10目录中的所有软件包。执行此命令会遍历所有子目录,编译其中的软件包并将它们安装到指定位置。这是一个脚本或命令,用于编译和安装Libccmio库。

源代码杀手的博客 1999

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

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

灵台方寸山斜月三星洞 559

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

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

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

小小默:进无止境 909

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

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

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

AlbenXie的博客 372

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

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

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

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

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

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

qq_33129875的博客 1679

设计模式之原型模式学习

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

Arrset的博客 260

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

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

weixin_61854715的博客 1171

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

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

qq_36425800的博客 504

设计模式学习之原型模式

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

weixin_34409741的博客 106

学习设计模式之原型模式

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

南淮北安的博客 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、付费专栏及课程。

余额充值
⌂ 换网址