设计模式-原型模式.ppt

  1. 1、本文档共27页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
设计模式 – 原型(Prototype)模式 Session3 By 佘丹 1st Jul 2008 原型(Prototype)模式 通过给出一个原型对象来指明所要创建的对象类型,然后用拷贝这个原型对象的办法创建出更多的同类型对象。 孙大圣的毫毛 孙悟空在与黄风怪的战斗中,“使一个身外身的手段:把毫毛揪下一把,用口嚼得粉碎,望上一喷,叫声‘变’,变有百十个行者,都是一样得打扮,各执一根铁棒,把那怪围在空中。”换而言之,孙悟空可以根据自己的形象,拷贝出很多“身外身”来。 孙悟空这种身外身的手段在面向对象设计领域里叫原型(Prototype)模式。 1,Java对原型模式的支持 在Java里面,我们可以通过Clone()方法实现原型模式。任何类,只要想支持克隆,必须实现Cloneable接口。Cloneable接口中有Clone方法,可以在类中复写实现自定义的克隆方法。克隆的实现方法有三种:浅拷贝、深拷贝和完全拷贝。 (1)浅拷贝 被拷贝对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。换言之,浅拷贝仅仅拷贝所考虑的对象,而不拷贝它所引用的对象。 (2)深拷贝 被拷贝对象的所有变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。那些引用其他对象的变量将指向被拷贝过的新对象,而不再是原有的那些被引用的对象。换言之,深拷贝把要拷贝的对象所引用的对象都拷贝了一遍。 (3)完全拷贝 完全拷贝不仅把要拷贝的对象所直接引用的对象都拷贝了一遍, 还把该对象间接引用到的所有对象也都拷贝了一遍。这是最彻底的一种拷贝。 2,Java的clone()方法 Clone protected Object clone() throws CloneNotSupportedException This method may be called to create a new copy of the Object. The typical behavior is as follows: o == o.clone() is false o.getClass() == o.clone().getClass() is true o.equals(o) is true However, these are not strict requirements, and may be violated if necessary. Of the three requirements, the last is the most commonly violated, particularly if the subclass does not override equals(Object) 55 . If the Object you call clone() on does not implement Cloneable (which is a placeholder interface), then a CloneNotSupportedException is thrown. Notice that Object does not implement Cloneable; this method exists as a convenience for subclasses that do. Objects implementation of clone allocates space for the new Object using the correct class, without calling any constructors, and then fills in all of the new field values with the old field values. Thus, it is a shallow copy. However, subclasses are permitted to make a deep copy. All array types implement Cloneable, and override this method as follows (it should never fail): public Object clone() { try { super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.getMessage()); } } 2,

文档评论(0)

junjun37473 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档