Prototype Design Pattern

It suggests, instead of creating a new instance of any object, make a copy of existing object and modify its properties as required. Generally cloning is used to create the copy of an existing object. 

Example

  • Drag ‘n Drop: While implementing drag and drop functionality in a UI, we need to show the shadow of items under dragging operation so that user can decide the place to drop the dragged item. Here instead of creating a new instance of item and setting the required properties, best way is to create a prototype of existing object and modify the required properties.
  • Filtered data set using same result set – We retrieved a large data as result set from database. Now we want to show different views on UI based on specified filter criteria. One way is to fetch the same data for every filter criteria, another way is to make the prototype of result set and apply filter to it. It will be less costly than repetitive database access. 

When to Use

  • When creating a new instance is much costly than creating the copy of an existing object like in case of result set.
  • When we need an exact copy of any object. 

Usage

  • Avoid the cost of recreating an object 

Drawbacks

  • Difficulty in adding clone or deep clone method in already existing classes.
  • If we are creating a prototype registry for easy access, a new instance of every object is required, which can be a performance overhead.
  • To copy the data of existing object, we should have sufficient access to the data or method of the class.

People who read this post also read :



0 comments:

Post a Comment