/**
* 属性更改支持器 用于被监测对象
*/
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();
好了,该说的都说完啦,转载还请注明出处哦,谢谢各位!^_^~
用javascript实现观察者模式
最新推荐文章于 2023-03-11 20:38:23 发布