Sunday, December 10, 2017

Decorator pattern Design Pattern In Java Script

Decorator pattern

Used to add new functionality to an existing object, without being obtrusive.

Example

In below example, we are adding addition functionality to task objects without changing behavior of existing object.

This allows to extended functionality of existing class without modifying the existing class and with out introducing any bugs into existing functionality.

In below example we are going to decorated Task that’s not going to change the way Task Works itself. But we are extending functionality of Task class.

We added new class urgentTask to extend Task functionality like set priority of task and notifying to important people.


var Task = function (name) {
this.name = name;
this.completed = false;
}
Task.prototype.complete = function () {
console.log('completing task: ' + this.name);
this.completed = true;
};
Task.prototype.save = function () {
console.log('saving Task: ' + this.name);
};
var myTask = new Task('Legacy Task');
myTask.complete();
myTask.save();
var UrgentTask = function (name, priority) {
Task.call(this, name);
this.priority = priority;
};
UrgentTask.prototype = Object.create(Task.prototype);
UrgentTask.prototype.notify = function () {
console.log('notifying important people');
}; 
UrgentTask.prototype.save = function () {
this.notify();
console.log('do special stuff before saving');
Task.prototype.save.call(this)
};

var ut = new UrgentTask('This is urgent', 1);
ut.complete();
ut.save();
console.log(ut); 


No comments:

Post a Comment