我做了一个observer的设计模式实现
version1
// -------------------------------------------------- function Subject(){} Subject.prototype.add = function(obj) { if(typeof(obj.update) === "function") { this.objects.push(obj); return true; } return false; } Subject.prototype.notify = function(subject) { for(var i in this.objects) { obj = this.objects[i]; obj.update(subject); } } // -------------------------------------------------- function Subject1() { Subject.call(this); this.objects = new Array(); this.message = "hello"; } Subject1.prototype = new Subject() Subject1.prototype.update = function(s) { if (s != null) this.message = s; this.notify(this); } // -------------------------------------------------- function Observer(){} Observer.prototype.update = function(subject) { alert(subject.message); } // -------------------------------------------------- var subject = new Subject1(); var observer = new Observer(); subject.add(observer); subject.update(); subject.update("same world");
version2
时间: 2024-10-08 12:37:30