Decorator模式参考图片:
代码:
var Component = function() {};
Component.prototype.operation = function() {};
var ConcreteComponent = function(){
this.operation = function() {
console.log("concrete component operation");
};
};
ConcreteComponent.prototype = new Component;
ConcreteComponent.prototype.constructor = ConcreteComponent;
var Decorator = function() {};
Decorator.prototype = new Component;
Decorator.prototype.constructor = Decorator;
Decorator.prototype.getComponent = function() {
return this.component;
};
Decorator.prototype.setComponent = function(o) {
this.component = o;
};
Decorator.prototype.operation = function() {
var component = this.getComponent();
if (component) {
component.operation();
}
};
var ConcreteDecoratorA = function(o) {
this.setComponent(o);
var ISuper = {
operation: this.operation
};
var addBehavior = function() {
console.log("concrete decoratorA behavior");
};
this.operation = function() {
ISuper.operation.call(this);
addBehavior();
};
};
ConcreteDecoratorA.prototype = new Decorator;
ConcreteDecoratorA.prototype.constructor = ConcreteDecoratorA;
var ConcreteDecoratorB = function(o) {
this.setComponent(o);
var ISuper = {
operation: this.operation
};
var addBehavior = function() {
console.log("concrete decoratorB behavior");
};
this.operation = function() {
addBehavior();
ISuper.operation.call(this);
};
};
ConcreteDecoratorB.prototype = new Decorator;
ConcreteDecoratorB.prototype.constructor = ConcreteDecoratorB;
var o = new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent()));
o.operation();