官术网_书友最值得收藏!

Prototype pattern

The prototype pattern is a pattern that seems more complicated than it really is. Practically, it is just a method to clone objects. Why would we need to clone objects when, these days, instantiating objects is not too costly in terms of performance? There are several situations in which it is required to clone objects that are already instantiated:

  • When the creation of a new object relies on an external resource or a hardware-intensive operation
  • When we need a copy of the same object with the same state without having to redo all of the operations to get to that state
  • When we need an instance of an object without knowing to which concrete class it belongs

Let's look at the following class diagram:

In the prototype pattern, the following classes are involved:

  • Prototype: This is the base class, or an interface that declares the clone() method that derived objects have to implement. In a simple scenario, we may not have a base class, and a direct concrete class is sufficient.
  • ConcretePrototype: These classes implement or extend the clone() method. This method should always be implemented because it returns a new instance of its type. If the clone() method was implemented in the base class and we didn't implement it in ConcretePrototype, when we invoked the clone() method on a ConcretePrototype object, it would return a base Prototype object.

The clone() method can be declared in an interface so classes implementing the method have to implement the method. This enforcement is done at compile time. However, it is not enforced on classes inherited from classes that implement the clone() method in hierarchies with more than one level.

主站蜘蛛池模板: 台山市| 九龙坡区| 宁城县| 磐安县| 汤原县| 连州市| 株洲县| 清新县| 昆山市| 潞城市| 乌鲁木齐市| 霍邱县| 民乐县| 新闻| 武宣县| 庆安县| 库车县| 安丘市| 疏勒县| 新巴尔虎左旗| 宣城市| 达州市| 庄河市| 大理市| 突泉县| 中山市| 温宿县| 清河县| 永新县| 蓝田县| 绥滨县| 潍坊市| 宜昌市| 湄潭县| 保德县| 浮梁县| 阳东县| 崇义县| 灌南县| 共和县| 云林县|