Created
March 6, 2013 02:46
-
-
Save kampfer/5096309 to your computer and use it in GitHub Desktop.
装饰器在js中的实现, 来自http://chrisincambo.wordpress.com/2008/06/23/decorator-pattern-in-javascript-gof-design-patterns/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Class to be decorated | |
function Coffee(){ | |
this.cost = function(){ | |
return 1; | |
}; | |
} | |
//Decorator A | |
function Milk(coffee){ | |
this.cost = function(){ | |
return coffee.cost() + 0.5; | |
}; | |
} | |
//Decorator B | |
function Whip(coffee){ | |
this.cost = function(){ | |
return coffee.cost() + 0.7; | |
}; | |
} | |
//Decorator C | |
function Sprinkles(coffee){ | |
this.cost = function(){ | |
return coffee.cost() + 0.2; | |
}; | |
} | |
//Here's one way of using it | |
var coffee = new Milk(new Whip(new Sprinkles(new Coffee()))); | |
alert( coffee.cost() ); | |
//Here's another | |
var coffee = new Coffee(); | |
coffee = new Sprinkles(coffee); | |
coffee = new Whip(coffee); | |
coffee = new Milk(coffee); | |
alert(coffee.cost()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment