2

我正在尝试让装饰器模式正常工作

http://www.joezimjs.com/javascript/javascript-design-patterns-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);?
4

1 回答 1

3

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

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

此外,请确保您的大小写是一致的。

于 2012-12-06T13:57:24.453 回答