我根据Head first Design Patterns一书制作了以下代码。
哪个代码是使用javascript修饰模式的最佳实现?
第一个和第二个代码的结果是相同的。
Fisrt示例代码与book相同的界面。
第二个与书有点不同,它分为两部分。
所以有三种选择。第一部分,第二部分1和第二部分。
我需要一个答案,其中一个是关于OOP和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());