When to use the Prototype pattern

The Prototype pattern is most useful in scenarios where you have an abstraction that will have varying characteristics between instances (or extensions) but does not require construction. At its core, the Prototype pattern really only refers to the extension mechanism (that is, via Object.create), so it can equally be used in any scenario where you have objects that may semantically relate to other objects via inheritance.

Imagine a scenario in which we need to represent sandwich data. Every sandwich has a name, a bread type, and three slots for ingredients. For example, here is the representation of a BLT:

const theBLT = {
name: 'The BLT',
breadType: 'Granary',
slotA: 'Bacon',
slotB: 'Lettuce',
slotC: 'Tomato'
};

We may wish to create an adaptation of the BLT, reusing most of its characteristics except the Tomato ingredient, which will be replaced with Avocado. We could simply clone the object wholesale, by using Object.assign to copy all the properties from theBLT to a fresh object and then specifically copying over (that is, overwriting) slotC:

const theBLA = Object.assign({}, theBLT, {
slotC: 'Avocado'
});

But what if the BLT's breadType was changed? Let's take a look:

theBLT.breadType = 'Sourdough';
theBLA.breadType; // => 'Granary'

Now, theBLA is out of sync with theBLT. We have realized that what we actually want  here is an inheritance Model so that breadType of theBLA will always match breadType of its parent sandwich. To achieve this, we can simply change our creation of theBLA so that it inherits from theBLT (using the Prototype pattern):

const theBLA = Object.assign(Object.create(theBLT), {
slotC: 'Avocado'
});

If we later change a characteristic of theBLT, it will helpfully be reflected in theBLA via inheritance:

theBLT.breadType = 'Sourdough';
theBLA.breadType; // => 'Sourdough'

This constructor-less Model of inheritance, as you can see, can be useful in some scenarios. We could equally represent this data using straightforward classes but with such basic data that may be overkill. The Prototype pattern is useful in that it provides a simple and explicit mechanism of inheritance that can result in less clunky code (although, equally, if misapplied, can lead to more complexity).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.62.94