Javascript--装饰器模式和观察者模式

装饰器模式

(function(){//装饰一棵树,装饰器模式通过对对象的属性进行改变来装饰对象。需要一个设置属性的方法
    var tree={};
    tree.decorate=function(){
        print("Make sure the tree won\'t fall");
    };

    tree.getDecorator=function(deco){
        tree[deco].prototype=this;
        return new tree[deco];
    };

    tree.RedBalls=function(){
        this.decorate=function(){
            this.RedBalls.prototype.decorate();
            print("Put on some red balls");
        }
    };

    tree.BlueBalls=function(){
        this.decorate=function(){
            this.BlueBalls.prototype.decorate();
            print("Add Blue Balls");
        }
    };

    tree.Angle=function(){
        this.decorate=function(){
            this.Angle.prototype.decorate();
            print("An angel on the top");
        }
    };

    tree=tree.getDecorator("BlueBalls");
    tree=tree.getDecorator("RedBalls");
    tree=tree.getDecorator("Angle");
    tree.decorate();
})();

观察者模式

(function(){    //观察者模式
    var observer={
        addSubscribe:function(callback){
            this.subscribers[this.subscribers.length]=callback;
        },
        removeSubscrible:function(callback){
            for(var i=0;i<this.subscribers.length;i++){
                if(this.subscribers[i]===callback){
                    delete(this.subscribers[i]);
                }
            }
        },
        publish:function(what){
            for(var i=0;i<this.subscribers.length;i++){
                if(typeof this.subscribers[i]==="function"){
                    this.subscribers[i](what);
                }
            }
        },
        make:function(o){
            for(var i in this){
                o[i]=this[i];
                o.subscribers=[];
            }
        }
    };

    //发布者
    var blogger={
        writeBlogPost:function(){
            var content="Today is "+new Date();
            this.publish(content);
        }
    }

    
    var la_time={
        newIssue:function(){
            var paper="Martians have landed on Earth!";
            this.publish(paper);
        }
    };

    observer.make(la_time);
    observer.make(blogger);
    //订阅者
    var jack={
        read:function(what){
            print("I just read " + what);
        }
    };

    var jill={
        gossip:function(what){
            print("You can not heard it from me but "+what);
        }
    }
    //增加订阅者
    blogger.addSubscribe(jack.read);
    blogger.addSubscribe(jill.gossip);
    blogger.writeBlogPost();
    //删除订阅者
    blogger.removeSubscrible(jill.gossip);
    blogger.writeBlogPost();

    la_time.addSubscribe(jill.gossip);
    la_time.newIssue();
})();

 

posted @ 2016-05-18 14:23  止水的水  阅读(604)  评论(0编辑  收藏  举报