`
lxiaodao
  • 浏览: 119694 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

EffectiveJava-第11条 谨慎地覆盖克隆clone

阅读更多
1、clone方法的通用约定是非常弱的
   x.clone()!=x
   x.clone().getClass()==x.getClass()
   x.clone().equals(x)
   都不是绝对的要求
  
2、Clone方法就是另一个构造器,你必须保证它不会伤害到原始的对象,并确保正确地创建被克隆对象中的约束条件。

3、clone架构与应用可变对象的final域的正常用法是不兼容的。

4、深度clone,典型例子HashTable
  
5、线程安全的类实现Cloneable接口,clone方法必须实现好同步:HashTable。
public class DeepClone {
   public  static void main(String[] arr){
	   Hashtable<String, Integer> table=new Hashtable<String, Integer>();
	   table.put("MM", 100);
	   
	   Hashtable<String, Integer> copytable=(Hashtable) table.clone();
	   System.out.println("----------mm----------"+copytable.get("MM"));
	   
	   
   }
}


总结:
 
(1)默认实现方式
   实现了Cloneable接口的类都应该有一个公用的方法覆盖clone:
   
   @Override public PhoneNumber clone() {
     super.clone();
   }
   此公有方法首先调用super.clone(),然后修正任何需要修正的域(浅克隆、深度克隆)。
(2)最佳实践
   实现对象的拷贝的好办法是提供一个拷贝构造器(copy constructor)或者拷贝工厂(copy factory)
   相比Cloneable/clone优点:
   不依赖于某一种很有风险的,语言之外的对象创建机制;
   不要求遵守尚未制定好的文档规范;
   不会与final域的正常使用发生冲突;
   不会抛出不必要的受检查异常CloneNotSupportedException;
   不需要强制进行类型转换;  
建议使用最佳实践
/**
 * 拷贝构造器(copy constructor)或者拷贝工厂(copy factory)展示
 * @author Administrator liuyang
 * Dec 23, 2009-12:05:00 AM
 */
public class GoodClone {
	private int type;
	private final String special;

	public GoodClone(int type, String spe) {
		this.type = type;
		this.special = spe;
	}
    /**
     * 拷贝构造器
     * @param good
     */
	public GoodClone(GoodClone good) {
		this.special = good.special;
		this.type = good.type;
	}
    /**
     * 拷贝工厂
     * @param good
     * @return
     */
	public static GoodClone newInstance(GoodClone good) {
		return new GoodClone(good.type, good.special);
	}

	public static GoodClone cloneInstance(GoodClone good) {
		return new GoodClone(good.type, good.special);
	}

	public static void main(String[] arr) {
		GoodClone entity = new GoodClone(10, "spacialGood");
		GoodClone copyEd1 = GoodClone.newInstance(entity);
		System.out.println("----------克隆方式newInstance-----------"
				+ (entity == copyEd1));

		GoodClone copyEd2 = new GoodClone(entity);
		System.out.println("----------克隆方式2-----------" + (entity == copyEd2));

		System.out.println("----------克隆方式1与克隆方式2-----------"
				+ (copyEd1 == copyEd2));
	}
}


0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics