JavaScript Basic Decorator Pattern


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function vehicle( vehicleType ){
  2. // properties and defaults
  3. this.vehicleType = vehicleType || 'car',
  4. this.model = 'default',
  5. this.license = '00000-000'
  6. }
  7. // Test instance for a basic vehicle
  8. var testInstance = new vehicle('car');
  9. console.log(testInstance);
  10. // vehicle: car, model:default, license: 00000-000
  11. // Lets create a new instance of vehicle, to be decorated*/
  12. var truck = new vehicle('truck');
  13. // New functionality we're decorating vehicle with
  14. truck.setModel = function( modelName ){
  15.  
  16. this.model = modelName;
  17. }
  18. truck.setColor = function( color ){
  19. this.color = color;
  20. }
  21.  
  22. // Test the value setters and value assignment works correctly
  23. truck.setModel('CAT');
  24. truck.setColor('blue');
  25. console.log(truck);
  26. // vehicle:truck, model:CAT, color: blue
  27. // Demonstrate 'vehicle' is still unaltered
  28. var secondInstance = new vehicle('car');
  29. console.log(secondInstance);
  30. // as before, vehicle: car, model:default, license: 00000-000

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.