设计模式-3-原型模式

来源:互联网 发布:知乎 室内环保 编辑:程序博客网 时间:2024/05/21 22:26

原型模式:通过复制一个现有的对象来生成新的对象,而不是通过实例化的方式

模型图:


package com.desinPattern;/**  * @author caoxuekun  * @version V1.0  * @Date 2017年7月20日 下午10:24:13   * 注意:  *      1.实现Cloneable接口。在java语言有一个Cloneable接口,它的作用只有一个,  * 就是在运行时通知虚拟机可以安全地在实现了此接口的类上使用clone方法。在java虚拟机中,  * 只有实现了这个接口的类才可以被拷贝,否则在运行时会抛出CloneNotSupportedException异常。  *      2.重写Object类中的clone方法,使其返回Portotype类对象  */  class Prototype implements Cloneable {          public Prototype clone(){              Prototype prototype = null;              try{                  prototype = (Prototype)super.clone();              }catch(CloneNotSupportedException e){                  e.printStackTrace();              }              return prototype;           }      }               public class Client {          public static void main(String[] args){          Prototype cp = new Prototype();           System.out.println("==="+cp);        for(int i=0; i< 10; i++){                  Prototype clonecp = (Prototype)cp.clone();                  System.out.println(clonecp);        }          }      }      /*===com.desinPattern.Prototype@6e00321com.desinPattern.Prototype@5ced6f0dcom.desinPattern.Prototype@6815ee24com.desinPattern.Prototype@77c5b2decom.desinPattern.Prototype@54624a40com.desinPattern.Prototype@f8db08com.desinPattern.Prototype@51f3eab7com.desinPattern.Prototype@64b6be69com.desinPattern.Prototype@198f1327com.desinPattern.Prototype@32728dcom.desinPattern.Prototype@6ffe8714 */

由输出对象的地址可以知道创建的是不同的对象