用javascript实现观察者模式

/**
 * 属性更改支持器 用于被监测对象
 */
var PropertyChangeSupport = function (object) {
    this.subject = object;
    this.listener = [];
};
PropertyChangeSupport.prototype.addPropertyChangeListener = function (listener) {
    this.listener.push(listener);
};
PropertyChangeSupport.prototype.firePropertyChange = function (propertyName, oldValue, newValue) {
    for(var i = 0;i<this.listener.length;i++){
        this.listener[i].propertyChange({propertyName:propertyName,oldValue:oldValue,newValue:newValue,src:this.listener[i]});
    }
};


/**
 * 属性更改监听器 给监测对象继承
 */
var PropertyChangeListener = function (func) {
    this.propertyChange = func;
};


/**
 * 被监测对象 孩子
 */
var Child = function () {
    this.support = null;
};
Child.prototype.addPropertyChangeListener = function (listener) {
    if (this.support == null)
        this.support = new PropertyChangeSupport(this);
    this.support.addPropertyChangeListener(listener);
};
Child.prototype.weakenUp = function () {
    console.log("我醒了");
    if(this.support !=null)
        this.support.firePropertyChange("weakenUp", "之前睡着", "现在醒了");
};
Child.prototype.laShiLe = function () {
    console.log("我拉屎了");
    if (this.support != null)
        this.support.firePropertyChange("laShiLe", "没拉", "拉了 床脏了");
};



/**
 * 监测对象 大人
 */ 
var Adult = function (name,callback) {
    this.name = name;
    PropertyChangeListener.call(this,function (obj) {
        callback.apply(this, [obj]);
    });
};



/**
 * 测试
 * new一个孩子类
 * 给它添加监测对象 爸爸和妈妈 并设置回调方法
 */
var child = new Child();
child.addPropertyChangeListener(new Adult("爸爸", function (obj) {
    console.log(obj.propertyName + " " + obj.newValue);
    if(obj.propertyName == "weakenUp")
        console.log(this.name + "说:傻B孩子,接着睡!");
    if(obj.propertyName == "laShiLe")
        console.log(this.name + "说:傻B孩子,弄得脏兮兮的!");
}));

child.addPropertyChangeListener(new Adult("妈妈", function (obj) {
    console.log(obj.propertyName + " " + obj.newValue);
    if (obj.propertyName == "weakenUp")
        console.log(this.name + "说:准备洗手吃饭了!");
    if (obj.propertyName == "laShiLe")
        console.log(this.name + "说:快给他洗洗!");
}));
child.weakenUp();
child.laShiLe();

好了,该说的都说完啦,转载还请注明出处哦,谢谢各位!^_^~
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值