原理

观察者模式是基于发布-订阅模式的。
区别在于发布-订阅模式。发布者和订阅者两者之间无关,通过一个媒介进行交互。
观察者模式有观察者和被观察者。被观察者应该存放着观察者,让被观察者状态发生变化时,要更新自己身上的所有观察者。
如下有个场景,被观察者:宝宝。观察者:父母。当宝宝状态发生变化时,父母接收到状态变化,并且更新。

被观察者

被观察者拥有以下的特征:

  • 自己的状态 state
  • 观察者队列
  • 设置观察者的方法
  • 改变自己状态的方法(变更状态并且通知观察者)

观察者

观察者拥有以下的特征:

  • 观察者接收到被观察者状态变更后触发更新

实现(ES6)

  1. class Subject {
  2. constructor() {
  3. //存放状态
  4. this.state = '开心';
  5. //存放观察者
  6. this.arr = []
  7. }
  8. attach(observer) {
  9. this.arr.push(observer);
  10. }
  11. setState(newState) {
  12. this.state = newState;
  13. this.arr.forEach(fn => fn.update(newState))
  14. }
  15. }
  16. class Observer {
  17. constructor(name) {
  18. this.name = name;
  19. }
  20. update(state){
  21. console.log(this.name + '-' +state)
  22. }
  23. }
  24. let baby = new Subject();
  25. let father = new Observer('父亲');
  26. let mother = new Observer('母亲');
  27. baby.attach(father);
  28. baby.attach(mother);
  29. baby.setState('大哭');//这时会执行观察者的更新函数

实现(ES5)

  1. function Subject() {
  2. this.state = "安静";
  3. this.arr = [];
  4. }
  5. Subject.prototype.attach = function (observer) {
  6. this.arr.push(observer);
  7. }
  8. Subject.prototype.setState = function (newState) {
  9. this.arr.forEach(observer => observer.update(newState))
  10. }
  11. function Observer(name){
  12. this.name = name;
  13. }
  14. Observer.prototype.update = function(newState){
  15. console.log(this.name + '-' + newState);
  16. }
  17. const baby = new Subject();
  18. const father = new Observer('爸爸');
  19. const mother = new Observer('妈妈');
  20. baby.attach(father);
  21. baby.attach(mother);
  22. baby.setState('大哭');