JS Structural pattern

by bhupendra negi

HTML

<h2>

</h2>
<!--
<ul>
<li>Structural
<ul>
<li> Decorator </li>
<li> Facade </li>
</ul>
</li>
</ul>
-->

JavaScript

// blueprint of objects are made up of , 
// how objects combined to form larger structure
// Decorator : extends functionality to an object without modifying it
// Facade : simplifies functionality

var Task = function(name) {
  this.name = name;
  this.completed = false;
};
Task.prototype.start = function() {
  console.log("Task started " + this.name);
}
Task.prototype.complete = function() {
  console.log("Task completed :" + this.name)
}

var t1 = new Task("Play");
t1.start();
t1.complete();

// now decorate object to add properties/methods

var t2 = new Task("Study for Exams");
t2.priority = 1;
t2.notify = function() {
  console.info(" Exam date approaching !");
};
t2.start();
t2.notify();
t2.complete();

// facade pattern
// use to provide simplicity to a complex system.
// its like entrance to the building , no matter how much choas inside would be , form outside all appears calm
// Jquery is a facade pattern

function Ftask(data) {
  this.name = data.name;
  this.priority = data.priority;
  this.project = data.project;
  this.user = data.user;
  this.completed = data.completed;
}

var TaskService = function() {
  return {
    complete: function(task) {
      task.completed = true
      console.log("completing :" + task.name);
    },
    notify: function(task) {
      console.info("Hey this task : " + task.name +
        "got completed")
    },
    save: function(task) {
      console.log(" Saivng this task :" + task.name + "In DB")
    },
    setCompletionDate: function(task) {
      task.date = new Date();
      console.log("Setting completion date to task " + task.name + "as :" + task.date);
    }
  }
}();

//now implement facade

var TaskServiceWrapper = function() {
var completeAndNotify = function(task) {
TaskService.complete(task);
if (task.completed === true){
TaskService.setCompletionDate(task);
TaskService.notify(task);
TaskService.save(task);
}
}
return {
completeAndNotify : completeAndNotify
}
}();


var task = new Ftask({
name:"Create...