观察者模式
观察者模式的简单实现
by Yoghurts
HTML
<div>
<div id = "subject"></div>
<div id = "control-box" >
<button id = "add">添加观察者</button>
<label for="">移除第<select name="" id="ObserversList"></select>个观察者</label>
<button id = "remove">确定</button>
</div>
</div>
<div id = "Observers_container">
</div>
CSS
.observer{
display: inline-block;
width:200px;
height: 100px;
margin:10px;
transition-duration: 1s;
-webkit-transition-duration:1s
}
#subject{
width:400px;
height: 200px;
margin:10px;
transition-duration: 1s;
-webkit-transition-duration:1s
}
JavaScript
/**
* 观察者模式的简单实现
*/
/**
* [观察者列表]
*/
function ObverserList(){
if(!(this instanceof ObverserList)){
return new ObverserList();
} else {
this.observers = [];
}
}
ObverserList.prototype.add = function(observer) {
this.observers.push(observer);
}
ObverserList.prototype.empty = function() {
this.observers = [];
}
ObverserList.prototype.indexOf = function(observer){
for(var i = 0; i < this.observers.length; i ++) {
if(observer === this.observers[i])
return i;
return -1;
}
}
ObverserList.prototype.get = function(index) {
if(index >= 0 && index < this.observers.length) {
return this.observers[index];
}
return null;
}
ObverserList.prototype.remove = function(observer) {
this.observers.splice(this.indexOf(observer), 1);
}
ObverserList.prototype.count = function() {
return this.observers.length;
}
/**
*[目标Object的实现]
*/
function Subject(){
if(!(this instanceof Subject)){
return new Subject();
} else {
this.obverserList = new ObverserList();
}
}
Subject.prototype.addObserver = function(observer){
this.obverserList.add(observer);
}
Subject.prototype.removeObserver = function(observer) {
this.obverserList.remove(observer);
}
Subject.prototype.empty = function(){
this.obverserList.empty();
}
Subject.prototype.notify = function(status){
//TODO
for(var i = 0; i < this.obverserList.count(); i ++) {
this.obverserList.get(i).update(status);
}
}
/**
* [Observer的实现]
*/
function Observer(){
if(!(this instanceof Observer)) {
return new Observer();
} else {
this.status = "";
}
}
Observer.prototype.update = function(status){
this.style.background = status;
}
function extend(obj, src) {
for(var item in src) {
if(!obj[item]) obj[item] = src[item];
}
}
function randomColor( ) {
var rand = Math.floor(Math.random( ) * 0xFFFFFF).toString(16);
if(rand.length == 6){
return rand;
}else{
return randomColor();
}
}
window.onload = function(){
var subject =...