Coding Guru

Code never does the mistake, we make the mistakes in the code. Think, Imagine, Phrase and then Code.

The Prototype Pattern

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

This particular pattern focuses on creating the object which can be used as a reference or blue print for the other objects to be created through the prototypal(in javascript inheritance is possible through prototyping only) inheritance. We create the new objects but instead of creating new non-initialized objects, we create the objects which are already defined in the blue print object. This pattern is also referred as Properties pattern.

We use this pattern where we have have some pre defined values or functions in the module but these are just the default ones which have to overridden. It's not the compulsion to override these but just a feature we can use. If the properties are not overridden by default it will be set to default, defined in the blue print object.

Diagram


Participants

The participating objects in this pattern are :

  • Client -- In sample code: the run() function.
    • it creates a new object by asking a prototype to clone itself
  • Prototype -- In sample code: CustomerPrototype
    • it creates an interfaces to clone itself
  • Clones -- In sample code: Customer
    • cloned objects which are being created


Sample code

we have a CustomerPrototype object which clones objects from a prototype object.Its constructor method accepts a prototype of type Customer.Calling the clone method will generate a new Customer object with its property values initialized with the prototype values.

This is the classical implementation of the Prototype pattern, but JavaScript can do this far more effectively using its built-in prototype facility.

function CustomerPrototype(proto) {
this.proto = proto;

this.clone = function () {
var customer = new Customer();

customer.first = proto.first;
customer.last = proto.last;
customer.status = proto.status;

return customer;
};
}

function Customer(first, last, status) {

this.first = first;
this.last = last;
this.status = status;

this.say = function () {
alert("name: " + this.first + " " + this.last +
", status: " + this.status);
};
}

function run() {

var proto = new Customer("n/a", "n/a", "pending");
var prototype = new CustomerPrototype(proto);

var customer = prototype.clone();
customer.say();
}


Advantages

  • New objects are created from the "blue print" of an existing object which inherit references to the existing functions in the prototype chain , thus boost the performance and keep the memory footprints to the minimum.
  • Very good for the applications where the focus is on object creation

Disadvantages

  • Overkill for the project which uses very less number of objects and does not have the emphasis on an extension of the prototype chains

Loading