javaScript设计模式---(观察者模式)
// 观察者模式 // 第一步 模拟一系列依赖Observer function ObserverList () { this.ObserverList = [] } ObserverList.prototype.add = function (obj) { this.ObserverList.push(obj) } ObserverList.prototype.Empty = function () { this.ObserverList = [] } ObserverList.prototype.Count = function () { return this.ObserverList.length } ObserverList.prototype.get = function (index) { if (index >= 0 && index < this.ObserverList.length) { return this.ObserverList[index] } } ObserverList.prototype.insert = function (index, obj) { var pointer = -1; if (index === 0) { this.ObserverList.unshift(obj) pointer = index } else if (index === this.ObserverList.length) { this.ObserverList.push(obj) pointer = index } return pointer } ObserverList.prototype.IndexOf = function (obj, startIndex) { let i = startIndex, pointer = -1; while (i < this.ObserverList.length) { if (obj = this.ObserverList[i]) { pointer = i } i++ } return pointer } ObserverList.prototype.RemoveIndexAt = function (index) { if (index === 0) { this.ObserverList.shift() } else if (index === this.ObserverList.length){ this.ObserverList.pop() } } // 使用extension拓展对象 function extend (obj, extension) { for (var key in obj) { extension[key] = obj[key] } } // 模拟目标(Subject)和在观察者列表上添加、删除或通知观察者 function Subject () { this.observers = new ObserverList() } Subject.prototype.AddObserver = function (observer) { this.observers.add(observer) } Subject.prototype.RemoveObserver = function (observer) { this.observers.RemoveIndexAt(this.observers.IndexOf(observer, 0)) } Subject.prototype.Notify = function (context) { var observerCount = this.observers.Count() for (let i = 0; i < observerCount; i++) { this.observers.get(i).Update(context) } }
后续继续学习~~~