初学es6写了个观察者模式,请多指教!!!!
2017-07-19 10:48
190 查看
/**
* Created by richard on 2017/7/19.
*/
console.log("------------observer观察者模式-------------");
class Observer{
constructor(){
this.handle = [];//相关订阅fn
}
addSubscribe(topic,fn){
this.handle.push({topic:topic,fn:fn});
console.log(this.handle);
}
removeSubscribe(topic,fn) {
let index ;
this.handle.forEach(function (data,i) {
if(data.topic==topic&&data.fn==fn){
index=i;
}
});
delete this.handle[index];
console.log(this.handle);
}
publish(topic,message){
this.handle.forEach(function(data){
if(data.topic==topic){
data.fn(message);
}
});
}
}
{
let test = new Observer();
let fn1 = function(data){
console.log(data);
}
let fn2 = function(data){
console.log("I'm in fn2 say "+data);
}
test.addSubscribe('abc',fn1);
test.addSubscribe('abc',fn2);
test.addSubscribe('abcd',fn2);
test.publish('abc','hello');
test.publish('abcd','good job');
test.removeSubscribe('abc',fn2);
test.publish('abc','fn2 you are here?')
}
console.log("--------------------------------------");
学习网址:http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html 特此感谢!
* Created by richard on 2017/7/19.
*/
console.log("------------observer观察者模式-------------");
class Observer{
constructor(){
this.handle = [];//相关订阅fn
}
addSubscribe(topic,fn){
this.handle.push({topic:topic,fn:fn});
console.log(this.handle);
}
removeSubscribe(topic,fn) {
let index ;
this.handle.forEach(function (data,i) {
if(data.topic==topic&&data.fn==fn){
index=i;
}
});
delete this.handle[index];
console.log(this.handle);
}
publish(topic,message){
this.handle.forEach(function(data){
if(data.topic==topic){
data.fn(message);
}
});
}
}
{
let test = new Observer();
let fn1 = function(data){
console.log(data);
}
let fn2 = function(data){
console.log("I'm in fn2 say "+data);
}
test.addSubscribe('abc',fn1);
test.addSubscribe('abc',fn2);
test.addSubscribe('abcd',fn2);
test.publish('abc','hello');
test.publish('abcd','good job');
test.removeSubscribe('abc',fn2);
test.publish('abc','fn2 you are here?')
}
console.log("--------------------------------------");
学习网址:http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html 特此感谢!
相关文章推荐
- es6 实例:使用Proxy实现观察者模式
- android观察者模式初学笔记
- 观察者模式--初学入门
- 初学设计模式【2】观察者模式——Observer
- 观察者模式之ES6实现(一)
- OpenJDK源码研究笔记(六)--观察者模式工具类(Observer和Observable)和应用示例
- 设计模式---观察者模式
- 设计模式---策略模式和观察者模式
- 设计模式:观察者模式
- Java-设计模式-观察者模式
- Java设计模式(五) Observer(观察者)模式及Tomcat引申
- 23种设计模式之观察者模式
- 搞清楚观察者模式
- 设计模式初学结束
- IOS 设计模式之三:(适配器模式 观察者 KVO)
- Android编程:观察者模式设计
- 观察者模式
- 设计模式学习笔记——观察者模式
- 设计模式—观察者模式(不)
- boost::signal2 信号/插槽(线程安全的观察者模式)