ruby、javascript、php中的观察者模式实现代码

2019-09-25 09:47:50于丽

    public function __construct() {
        $this->_observers = array();
    }
    public function add_observer($obs) {
        $this->_observers[] = $obs;
    }
    public funtion delete_observer($bos) {
        $index = array_search($bos, $this->_observers);
        unset($this->_observers[$index]);
    }
    public function notify_observers() {
        foreach($this->_observers as $v) {
            $v->update();
        }
    }
}
//观察者
class Observer
{
    public function __construct() {
        do sth;
    }
    public function update() {
        do sth;
    }
}
//实例
$sub = new Subject();
$obs = new Observer();
$sub->add_observer($obs);
$sub->notify_observers();

js实现

js实现起来也不麻烦,就是得写些工具函数方便用,比如删除数组指定的元素。下面只用最简单的实现方法。

//被观察者
function Subject() {
    var _this = this;
    this.observers = [];
    this.addObserver = function(obj) {
        _this.observers.push(obj);
    }
    this.deleteObserver = function(obj) {
        var length = _this.observers.length;
        for(var i = 0; i < length; i++) {
            if(_this.observers[i] === obj) {
                _this.observers.splice(i, 1);
            }
        }
    }
    this.notifyObservers = function() {
        var length = _this.observers.length;
        console.log(length)
        for(var i = 0; i < length; i++) {
            _this.observers[i].update();
        }
    }
}
//观察者
function Observer() {
    this.update = function() {