前言

  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()办法

@Overridepublic 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相干技术文章或行业资讯,欢送大家关注和转发文章!