zoukankan      html  css  js  c++  java
  • 创建型---prototype模式

    • 代码:
     1 package com.design;
     2 import java.util.ArrayList;
     3 
     4 /**
     5  * 
     6  * @author Administrator
     7  *
     8  */
     9 class ConcretePrototype implements Cloneable { 
    10     /**
    11      * 成员变量
    12      * namelist 测试深拷贝 
    13      */
    14     private ArrayList<String> nameList = new ArrayList<String>(); 
    15     
    16     /**
    17      * 构造函数
    18      */
    19     public ConcretePrototype() { 
    20       } 
    21     
    22     /**
    23      * 添加name到namelist
    24      * @param name
    25      */
    26     public void setName(String name) { 
    27         this.nameList.add(name); 
    28       } 
    29     
    30      /**
    31       *  获取namelist
    32       * @return
    33       */
    34      public ArrayList<String> getNameList() { 
    35         return this.nameList; 
    36       } 
    37       
    38      /**
    39       * 覆盖Object基类中的clone()方法,并扩大该方法的访问权限,具体化返回本类型 
    40       */
    41      public ConcretePrototype clone() {
    42          
    43         ConcretePrototype self = null;   
    44         try
    45         {
    46             self = (ConcretePrototype) super.clone();
    47             ///以下这句是实现深拷贝的关键 
    48             self.nameList = (ArrayList<String>) this.nameList.clone();
    49         }
    50         catch(CloneNotSupportedException e)
    51         {
    52             e.printStackTrace();
    53         }
    54         
    55         return self;
    56       } 
    57 } 
    58 
    59 //测试类 
    60 public class Test { 
    61       public static void main(String[] args) { 
    62         ConcretePrototype prototype = new ConcretePrototype();
    63         prototype.setName("蚂蚁 ...");
    64         System.out.println("prototype : " + prototype.getNameList()); 
    65          
    66         ///通过clone获得一个拷贝 
    67         ConcretePrototype fromClone = prototype.clone(); 
    68         fromClone.setName("小蚂蚁 ..."); 
    69         System.out.println("fromClone : " + fromClone.getNameList());
    70         System.out.println("prototype : " + prototype.getNameList()); 
    71       } 
    72 }
    • 结果:

    prototype : [蚂蚁 ...]
    fromClone : [蚂蚁 ..., 小蚂蚁 ...]
    prototype : [蚂蚁 ...]

  • 相关阅读:
    (24)码表
    (23)IO之打印流 PrintStream & Printwriter
    (22)Properties,这不会Io流中的类,但是通常和IO流中的一些流配合使用
    (21)IO流之对象的序列化和反序列化流ObjectOutputStream和ObjectInputStream
    (20)IO流之SequenceInputStream 序列流
    01.vue基础
    02.1插值操作-Mustache语法
    jQuery对节点的增删改查和一些常用的逻辑处理
    递归 阶乘
    电脑远程连接
  • 原文地址:https://www.cnblogs.com/renhl/p/4475060.html
Copyright © 2011-2022 走看看