Prototype es un patr贸n de dise帽o creacional que permite la clonaci贸n de objetos, incluso los complejos, sin acoplarse a sus clases espec铆ficas.
Todas las clases prototipo deben tener una interfaz com煤n que haga posible copiar objetos incluso si sus clases concretas son desconocidas. Los objetos prototipo pueden producir copias completas, ya que los objetos de la misma clase pueden acceder a los campos privados de los dem谩s.
/** * The example class that has cloning ability. We'll see how the values of field * with different types will be cloned. */classPrototype {public primitive:any;public component:object;public circularReference:ComponentWithBackReference;publicclone():this {constclone=Object.create(this);clone.component =Object.create(this.component);// Cloning an object that has a nested object with backreference// requires special treatment. After the cloning is completed, the// nested object should point to the cloned object, instead of the// original object. Spread operator can be handy for this case.clone.circularReference = {...this.circularReference, prototype: { ...this }, };return clone; }}classComponentWithBackReference {public prototype;constructor(prototype:Prototype) {this.prototype= prototype; }}/** * The client code. */functionclientCode() {constp1=newPrototype();p1.primitive =245;p1.component =newDate();p1.circularReference =newComponentWithBackReference(p1);constp2=p1.clone();if (p1.primitive ===p2.primitive) {console.log('Primitive field values have been carried over to a clone. Yay!'); } else {console.log('Primitive field values have not been copied. Booo!'); }if (p1.component ===p2.component) {console.log('Simple component has not been cloned. Booo!'); } else {console.log('Simple component has been cloned. Yay!'); }if (p1.circularReference ===p2.circularReference) {console.log('Component with back reference has not been cloned. Booo!'); } else {console.log('Component with back reference has been cloned. Yay!'); }if (p1.circularReference.prototype===p2.circularReference.prototype) {console.log('Component with back reference is linked to original object. Booo!'); } else {console.log('Component with back reference is linked to the clone. Yay!'); }}clientCode();
Output.txt: Resultado de la ejecuci贸n
Primitive field values have been carried over to a clone. Yay!
Simple component has been cloned. Yay!
Component with back reference has been cloned. Yay!
Component with back reference is linked to the clone. Yay!