简体   繁体   中英

How to implement the Decorator Design pattern in javascript?

Could anybody help me to implement the Decorator design pattern in javascript. I have a TankBase entity:

TankBase = function (x, y, width, height, direction, imageOptions) {
    TankBase.base.call(this, x, y, width, height, imageOptions);
    this.speed = 250;
    this.direction = direction;
    this.render = function (drawEngine) {
        drawEngine.render();
    };
    ...
}

I want to add a new functionality using the Decorator pattern. For example, I want to modify the render() function and draw a health indicator under a tank:

var TankHealthDecorator = function (tank) {
    var _tank = tank;
    this.render = function (drawEngine) {
        // draw a health indicator
        ...
        _tank.render(drawEngine);
    };
}

Usage:

var tank = new TankHealthDecorator(new HeavyTank());

where HeavyTank inherits TankBase.

How should I modify TankHealthDecorator() to use it like a wrapper for a tank instance?

EDIT:

Thank you, Paul, for a great article:

I would start here: addyosmani.com/blog/decorator-pattern Good write up. – Paul

Functionally I think what you have is pretty close. I'd store off the original render function, assign a new one, and then simply apply it from within the decorated one. I also don't see a need to create the decorator as an object, but that's probably more of a preference thing.

var DrawEngine = { render: function() {
    console.log('render');
} };

var TankBase = function (x, y, width, height, direction, imageOptions) {
    this.speed = 250;
    this.direction = direction;
    this.render = function (drawEngine) {
        drawEngine.render();
    };
};

var HeavyTank = function() {
    TankBase.apply(this, arguments);
    this.render = function() {
        console.log('heavyTank Render');
    }
}

function DecorateTankWithHealthIndicator (tank) {
    var oRender = tank.render;
    tank.render = function (drawEngine) {
        console.log('draw a health indicator');
        oRender.apply(tank, arguments);
    };
};

var btank = new TankBase();
var htank = new HeavyTank();
btank.render(DrawEngine);
htank.render(DrawEngine);
DecorateTankWithHealthIndicator(btank);
DecorateTankWithHealthIndicator(htank);
btank.render(DrawEngine);
htank.render(DrawEngine);

In the following approach a tankBase object gets passed to the tankHealth function. The tankBase object gets modified within the tankHealth function, saving the tankBase object in the var that . After the modification that gets returned as the modified tankBase object.

var TankBase = function () {
        this.render = function () {
            console.log('tankBase')
        };
    }

var TankHealthDecorator = function (tank) {
    var that = tank;

    that.render = function() {
        console.log('tankHealth')
    };

    return that;
}

window.onload = function(){
    var tankBase = new TankBase();
    var testHealth = new TankHealthDecorator(new TankBase());

    tankBase.render();     // tank base
    testHealth.render();   // tank health
};

The Decorator Pattern

Here is a rough implementation of the Decorator Pattern -- AKA: Wrapper :

Background:

The Decorator Pattern is typically used to add additional responsibilities to an object dynamically by forwarding requests onto its accepted Component, and|or decouple Deep Inheritance Hierarchies to be Compositive in Type (not to be confused with the Composite Pattern -- which is Compositive in Hierarchy -- using a Component-Leaf structure to allow synonymous requests across a uniform, fractal topology [treating parents & children equally]).

function AbstractComponent(){
    this.draw = function(){
        console.log('@AbstractComponent | #draw');
    };
}

function AbstractDecorator(){
    AbstractComponent.call(this);  // Inherit AbstractComponent Interface
    this.notify = function(){
        console.log('@AbstractDecorator | #notify');
    };
}

function ConcreteComponent(options){
    AbstractComponent.call(this);  // Inherit AbstractComponent Interface
    this.fill = function(){
        console.log('@ConcreteComponent | #fill');
    };
}

function ConcreteDecorator(Component){
    AbstractDecorator.call(this);  // Inherit AbstractDecorator Interface
    function PrivateResponsibility(){
        console.log('@ConcreteDecorator | #PrivateResponsibility');
    }
    this.additionalResponsibility = function(){
        console.log('@ConcreteDecorator | #additionalResponsibility');
    };
    this.draw = function(){
        console.log('@ConcreteDecorator | #draw-Component.draw');
        // ... additional logic
        PrivateResponsibility();
        Component.draw();
    };
    this.fill = function(){
        console.log('@ConcreteDecorator | #fill-Component.fill');
        Component.fill();
    };
}

var concreteComponent = new ConcreteComponent();
concreteComponent = new ConcreteDecorator(concreteComponent);  // use same variable name as to allow client code to remain the same

//CLIENT CODE
concreteComponent.draw();
concreteComponent.fill();
concreteComponent.notify();
concreteComponent.additionalResponsibility();

Following is my understanding about function(object) decoration

 function api_decorator(some_data){
     return function decorator(func){
        return function new_function(args){
         /* do somethinfg with data before and after func */
         console.log("I'm code before with data: "+some_data);
         func(args);
         console.log("I'm code after");
    }
  }
}

function somefunc(data){
    console.log("Hi, I'm func "+data);
}

somefunc("without decoration")
/* injecting somefunc in decorator api */
somefunc=api_decorator("data needed for api")(somefunc)
/* calling decorated with api somefunc */
somefunc("with decoration")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM