观察者模式

image.png

  1. //类似于模型层
  2. class Subject{
  3. constructor() {
  4. this.state = 0;
  5. this.observers = [];
  6. }
  7. getState() {
  8. return this.state;
  9. };
  10. setState(state) {
  11. this.state = state;
  12. this._notifyAllObservers();
  13. };
  14. attach(observer) {
  15. this.observers.push(observer);
  16. };
  17. remove(observer) {
  18. const index = this.observers.find((el) => {
  19. return el == observer;
  20. });
  21. this.observers.splice(index, 1);
  22. };
  23. _notifyAllObservers() {
  24. this.observers.forEach((observer) => {
  25. observer.update();
  26. })
  27. };
  28. }
  29. //类似于视图层
  30. //实例化对象,就会自动把观察者对象放到subject队列里。
  31. class Observer{
  32. constructor(name, subject) {
  33. this.name = name;
  34. this.subject = subject;
  35. this.subject.attach(this);
  36. }
  37. update() {
  38. console.log(`name:${this.name}, state:${this.subject.getState()}`);
  39. }
  40. }
  41. const subject = new Subject();
  42. const observer1 = new Observer('观察者1', subject);
  43. const observer2 = new Observer('观察者2', subject);
  44. const observer3 = new Observer('观察者3', subject);
  45. subject.remove(observer3);
  46. subject.setState(1);
  47. subject.setState(2);

参考

https://www.youtube.com/watch?v=W5OHcEuLIyg