网上许多关于原型模式的文章东西倒是说了很多而且还扯到了工厂模式等一些其他的模式,
我个人认为那样真是啰嗦的要死不说还把问题搞负责了。
克隆分为浅克隆和深克隆,浅克隆紧紧克隆对象的基本数据类型的值,深克隆会连引用类型也克隆。JAVA中凡是实现了java.lang.Cloneable接口的类都具有克隆功能,而这样的克隆是浅克隆的,深克隆的原理是:通过把克隆对象序列化到内存然后再反序列化读出。
package design.prototype; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author 作者 E-mail: [email protected] * @version 创建时间:2012-1-12 下午10:55:57 <br> */ public class Person implements Cloneable, Serializable { public Map<String, String> map = new HashMap<String, String>();; @Override protected Object clone() throws CloneNotSupportedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray()); ois = new ObjectInputStream(bais); return ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (oos != null) try { oos.close(); } catch (IOException e) { e.printStackTrace(); } if (ois != null) try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }
深克隆也叫做完整克隆,我想浅克隆那就应该称作部分克隆了吧。下面是HashMap的clone方法
/** * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and * values themselves are not cloned. * * @return a shallow copy of this map. */ public Object clone() { HashMap<K,V> result = null; try { result = (HashMap<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // assert false; } result.table = new Entry[table.length]; result.entrySet = null; result.modCount = 0; result.size = 0; result.init(); result.putAllForCreate(this); return result; }