JavaScript装饰模式

时间:2012-12-06 13:51:51

标签: javascript design-patterns decorator

我正试图让装饰模式在下面工作

http://www.joezimjs.com/javascript/javascript-design-patterns-decorator/

我可能错过了一些观点,但这种模式并不像我期望的那样有效。

如果我添加两个装饰器并将它们添加到类中,则不会像我想象的那样传递函数。只能调用最后一个装饰器的函数或调用基本的Decorator。链条坏了。我该如何解决这个问题?

我添加了一个小提琴:

http://jsfiddle.net/hbyLW/25/

更新:更正版本

http://jsfiddle.net/hbyLW/29/

源代码:

// A basic device class
var device = function(options) {
    this.brightness = options.brightness;
    this.Id = options.Id;
    this.motion = options.motion;
};

// Adding some functions to the class
device.prototype = {

    getID: function() {
        console.log("This ID:" + this.device.Id);
        return this.Id;
    },
    getBrightness: function() {
        console.log("This Brightness: " + this.brightness);
        return this.brightness;
    },
    getMotion: function() {
        console.log("This Motion: " + this.motion);
        return this.motion;
    }
};

// A device Decorator 
var deviceDecorator = function(device) {
    this.device = device;
};

// Adding pass through functions to the Decorator
deviceDecorator.prototype = {
    getId: function() {
        console.log("Old Id");
        return this.device.getId;
    },
    getBrightness: function() {
        console.log("Old Brightness");
        return this.device.getBrightness;
    },
    getMotion: function() {
        console.log("Old Motion");
        return this.device.getMotion;
    }
};

// A Decorator that adds some functionality to the getBrightness function
var brightnessDecorator = function(device) {
    deviceDecorator.call(this, device);
};

brightnessDecorator.prototype = new deviceDecorator();

brightnessDecorator.prototype.getBrightness = function() {
    this.device.getBrightness();
    console.log("Changed Brightness");
};

var motionDecorator = function(device) {
    deviceDecorator.call(this, device);
};

// A Decorator that adds some functionality to the getMotion function
motionDecorator.prototype = new deviceDecorator();

motionDecorator.prototype.getMotion = function() {
    this.device.getMotion();
    console.log("changed Motion");
};

// Some options for a device
var options = {
    Id: "Identifier",
    brightness: true,
    motion: false
};

// Create a new device
var Lamp = new device(options);
// Add the decorators to the device
Lamp = new brightnessDecorator(Lamp);
Lamp = new motionDecorator(Lamp);

// Executing the functions
Lamp.getId();
Lamp.getMotion();
Lamp.getBrightness();
console.log(Lamp);?

1 个答案:

答案 0 :(得分:3)

你的第一个装饰者返回device.getID(函数本身),而不是调用它并返回它返回的值。

deviceDecorator.prototype = {
  getID: function() {
    console.log("Old Id");
    return this.device.getID(); // <= call function instead of returning it
  },
  ...
}

另外,请确保您的大写一致。