dimanche 5 mars 2017

Which code is the best? I am learning Decorate pattern with javascript

I made below codes based on Head first Design Patterns book.

Which code is the best implementation for decorate pattern with javascript??

The result of first and second code is same.

Fisrt example code has same interface compare to book.

Second one is a little bit different from book and it divided two part.

So There is three options. First one, Second part1 and Second part2.

I need an answer which one is the beset in regard to the OOP and javascript.

Thax!

function DarkRoast(){
        this.description = 'Dark Roast';
  this.cost = function(){
        return 2;
  }
  this.getDescription = function(){
        return this.description;
  }
}

function HouseBlend(){
        this.description = 'House Blend';
  this.cost = function(){
        return 1;
  }
  this.getDescription = function(){
        return this.description;
  }
}

function Mocha(beverage){
        this.getDescription = function(){
        return beverage.getDescription() + ', Mocha'
  }
  this.cost = function(){
        return beverage.cost() + 0.5;
   }
}

function Whip(beverage){
        this.getDescription = function(){
        return beverage.getDescription() + ', whip'
  }
  this.cost = function(){
        return beverage.cost() + 0.7;
   }
}
// EX1
var beverage1 = new DarkRoast();
beverage1 = new Mocha(beverage1);
beverage1 = new Mocha(beverage1);
beverage1 = new Whip(beverage1);
console.log(beverage1.getDescription(),beverage1.cost());
var beverage2 = new HouseBlend();
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
console.log(beverage2.getDescription(),beverage2.cost());
function Beverage(name, cost){
        this.description = name;
  this.cost = function(){
        return cost;
  }
  this.getDescription = function(){
        return this.description;
  }
}
function AddSome(beverage, name, cost){
        this.getDescription = function(){
        return beverage.getDescription() + ', ' + name;
  }
  this.cost = function(){
        return beverage.cost() + cost;
  }
}

var darkRoast = function(){
        return new Beverage('Dark Roast',2);
}
var moch = function(beverage){
        return new AddSome(beverage, 'Mocha', 0.5);
}
var whip = function(beverage){
        return new (AddSome.bind(null, beverage, 'Whip', 0.7))();
}

// EX2 part1
var beverage1 = darkRoast();
beverage1 = moch(beverage1);
beverage1 = moch(beverage1);
beverage1 = whip(beverage1);
console.log(beverage1.getDescription(),beverage1.cost());

// EX2 part2
var beverage2 = new Beverage('House Blend',1);
beverage2 = new AddSome(beverage2, 'Mocha', 0.5);
beverage2 = new AddSome(beverage2, 'Whip', 0.7);
console.log(beverage2.getDescription(),beverage2.cost());

Aucun commentaire:

Enregistrer un commentaire