我做了一个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
Original: https://www.cnblogs.com/code-style/p/4235781.html
Author: codestyle
Title: JavaScript的OOP编程2
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/536004/
转载文章受原作者版权保护。转载请注明原作者出处!