原型模式Prototype与 JavaScript的Prototype继承

Quotedfromhttp://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html

5、原型模式(Prototype)

原型模式虽然是创建型的模式,但是与工程模式没有关系,从名字即可看出,该模式的思想就是将一个对象作为原型,对其进行复制、克隆,产生一个和原对象类似的新对象。本小结会通过对象的复制,进行讲解。在Java中,复制对象是通过clone()实现的,先创建一个原型类:

https://www.tutorialspoint.com/design_pattern/prototype_pattern.htm

Prototypepatternreferstocreatingduplicateobjectwhilekeepingperformanceinmind.Thistypeofdesignpatterncomesundercreationalpatternasthispatternprovidesoneofthebestwaystocreateanobject.

Thispatterninvolvesimplementingaprototypeinterfacewhichtellstocreateacloneofthecurrentobject.Thispatternisusedwhencreationofobjectdirectlyiscostly.Forexample,anobjectistobecreatedafteracostlydatabaseoperation.Wecancachetheobject,returnsitscloneonnextrequestandupdatethedatabaseasandwhenneededthusreducingdatabasecalls.

从上面的解释中可以看出设计模式中创建型(CreationalPatterns)模式中的prototype其实跟JavaScriptprototype继承中的prototype概念是一致的,是同一种思想。只是设计模式里面的说的是一个通用的模式来创建一个耗时对象,而JavaScript则是通过prototype方式来实现面向对象的继承,是从面向对象继承的方面来讨论的,但是2者的本质上就是通过对象复制来创建新对象。

相关推荐