Prototype Pattern

The prototype pattern Prototype Pattern uses a prototype instance to point to the class that creates objects, and is used to share prototype properties and methods of classes that create new objects.

Description

In JavaScript, its unique prototype inheritance feature can be used to create objects, that is, creating an object as the value of the prototype property of another object. The prototype object effectively utilizes the objects created by each constructor, extracting common properties and methods between instances into shared properties and methods, which can be shared by instances.
In Java, it is usually used to specify the type of object to be created by the prototype instance, and new objects are created by copying these prototypes. Specifically, it involves implementing the Cloneable interface in an abstract class and overriding the clone method in the Object class. Then, subclasses can inherit this abstract class and use a collection class such as HashTable to store in a cache class. When a class is needed, it can be found in the HashTable and a new subclass can be obtained through clone using the prototype pattern to create objects is much more efficient than directly using the new keyword, because the clone method of the Object class is a native method that directly operates on the binary stream in memory. The performance difference is particularly noticeable when copying large objects. Another benefit of using the prototype pattern is to simplify the creation of objects, making it as simple as copying and pasting when editing a document. Therefore, when there is a need to repeatedly create similar objects, the prototype pattern can be considered. In addition, in the context of deep copy and shallow copy issues, deep copy occurs with 8 basic types in Java and their wrapper types as well as the String type, while everything else is shallow copy.

Advantages

  • Improved performance.
  • Avoids the constraints of constructors.

Disadvantages

  • All the functionality of all classes need to be considered in the prototype.
  • The creation of objects does not invoke the class's constructor.

Implementation

var Shape = {
    name : null,
    say: function(){
        console.log(this.name);
    }
}

var rectangle = Object.create(Shape);
rectangle.name = "Rectangle";
rectangle.say(); // Rectangle

var square = Object.create(Shape);
square.name = "Square";
square.say(); // Square

var circle = Object.create(Shape);
circle.name = "Circle";
circle.say(); // Circle

Every Day a Question

https://github.com/WindrunnerMax/EveryDay

References

https://segmentfault.com/a/1190000012427846 https://www.runoob.com/design-pattern/prototype-pattern.html https://wiki.jikexueyuan.com/project/java-design-pattern/prototype-pattern.html