- 代码:
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 : [蚂蚁 ...]
时间: 2024-10-06 00:29:18