/ Published in: JavaScript
In this section we're going to explore the decorator - a structural design pattern that promotes code reuse and is a flexible alternative to subclassing. This pattern is also useful for modifying existing systems where you may wish to add additional features to objects without the need to change the underlying code that uses them.
Traditionally, the decorator is defined as a design pattern that allows behavior to be added to an existing object dynamically. The idea is that the decoration itself isn't essential to the base functionality of an object otherwise it would be baked into the 'superclass' object itself.
Traditionally, the decorator is defined as a design pattern that allows behavior to be added to an existing object dynamically. The idea is that the decoration itself isn't essential to the base functionality of an object otherwise it would be baked into the 'superclass' object itself.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function vehicle( vehicleType ){ // properties and defaults this.vehicleType = vehicleType || 'car', this.model = 'default', this.license = '00000-000' } // Test instance for a basic vehicle var testInstance = new vehicle('car'); console.log(testInstance); // vehicle: car, model:default, license: 00000-000 // Lets create a new instance of vehicle, to be decorated*/ var truck = new vehicle('truck'); // New functionality we're decorating vehicle with truck.setModel = function( modelName ){ this.model = modelName; } truck.setColor = function( color ){ this.color = color; } // Test the value setters and value assignment works correctly truck.setModel('CAT'); truck.setColor('blue'); console.log(truck); // vehicle:truck, model:CAT, color: blue // Demonstrate 'vehicle' is still unaltered var secondInstance = new vehicle('car'); console.log(secondInstance); // as before, vehicle: car, model:default, license: 00000-000