Prototype design mode implementation

zhaozj2021-02-16  60

Prototype design mode implementation

Implementing the prototype design pattern

Download this article code

When I build an instance of a class is very complicated, we can use the prototype mode. An instance of a large number of classes is established, it is better to use the original copy of the original instance after appropriate modification. Using the prototype mode, you can reduce the number of subclasses by cloning a prototype. Prototype mode can reduce the number of instances of classes.

In this mode, the object is created by cloning. We sometimes create a lot of subclasses, in addition to creating different objects through a lot of subclasses, we can only need a single subclass, this subclass keeps a reference to each object base class, and created through this subclass Object. Parameters and cloned the object by transmitting the parameters and cloned the object. Each object implements a Clone method, so it can be cloned. We can use the prototype mode to reduce the number of subclasses by cloning prototypes.

Clones can be implemented by implementing the IcloneAble interface. The only way in the iCloneable interface is Clone and returns an instance of a new class.

Icloneable.clone method Signature [VisualBasic] Function Clone () as object [c #] Object Clone ();

We must understand that the clone () method is just a shallow copying, not deep copy (Deep Copy). So it just returns a reference, not an instance of a replication as deep copy (Deep Copy). We can implement deep replication (Deep Copy) by using the iSerializable interface.

Another disadvantage is that each subclass of the prototype must implement Clone () method, sometimes, adding a Clone method is difficult.

In this example, I built the Empdata class and implemented the Icloneable interface and the iSerializable interface. The iCloneable interface needs to implement a Clone method so that the class can be copied. The iSerializable interface in order to achieve deep replication of EMPDATA classes (DEEP COPY). The method used is: Sequence of EMPDATA objects into a file, or the file is also sequenced into an EMPDATA object.

The EmpData class contains two methods: GetEmpData and Changeempdata. These two methods are used to get the EMPDATA object in a string (String), change the EMPDATA class. Each method can be called to verify the difference between Shallow Copy and Deep Copy. When the EMPDATA class changes, this change occurs simultaneously in the clone object of EmpData; in deep copy, this change does not appear when the EmpData object changes. Empdata's cloned object.

The constructor of the EMPDATA class reads the XML file and creates an EMP object.

See (2)

转载请注明原文地址:https://www.9cbs.com/read-23472.html

New Post(0)