Builder Pattern, and Prototype Pattern
It separates the construction of complex object from its representation, so that number of different representations can be build based on the requirement. It is similar to factory pattern, but it does not return simple descendant of base class. The factory is concerned with what is made and the builder with how it is made. Factory simply returns an instance of related class of base type, but builder returns a composition of various classes depending on the specified state.
- Editor Builder: Suppose you are creating a UI for workflow where a number of different types of nodes can exist. We need different editors to edit these nodes, which can be very complex in structure. Here we can use builder which can build the desired editor. Even editors can vary in structure based on current state of system.
When to Use
- When we have a complex UI element to build whose structure and composition may vary depending on the system state.
- When we want to isolate and abstract the complex UI building mechanism from rest of the system.
- A Builder helps you vary the internal presentation of the product it builds.
- It hides the detail of how the product is assembled.
- Builder build the final product step by step based on data given, so we have more control over the final product.
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.
- 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.
- Avoid the cost of recreating an object
- 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.