Javascript 观察者模式 -- 发布订阅模式

版权声明:本文为博主原创文章,如需转载,请注明出处。 https://blog.csdn.net/WestLonly/article/details/79943925
  • 观察者模式 – 发布订阅模式

    • 观察者模式 : 一个对象(称为 subject )维持一系列依赖于它( 观察者 )的对象,将有关状态的任何变动自动通知给他们,来通过代码实现一个现实生活中的例子 : 听到孩子哭了,他爸去喂奶,她妈跑路 的例子,
      整个过程而言,首先,孩子要哭,哭了之后,她爸妈都听见,听见之后,她爸妈做出不同的反应.这种反应就是 : 他爸去喂奶,她妈跑路

      class Son {
          constructor( dad, mom ) {
              this.dad = dad;
              this.mom = mom;
              this.cry = () => {
                  console.log( '孩子哭了' );
                  this.dad.notice();
                  this.mom.notice();
              };
          }
      }
      
      class Father {
          constructor() {
              this.notice = () => {
                  console.log( '他爸听到孩子哭了' );
                  this.food();
              };
              this.food = () => {
                  console.log( '他爸要去喂奶了' );
              };
          }
      }
      
      class Mother {
          constructor() {
              this.notice = () => {
                  console.log( '她妈听到孩子哭了' );
                  this.goAway();
              };
              this.goAway = () => {
                  console.log( '她妈跑路了' );
              };
          }
      }
      
      let father = new Father();
      let mother = new Mother();
      let son = new Son( father, mother );
      setTimeout( function () {
          son.cry();
      }, 500 );
      

      输出结果为 :

          孩子哭了
          他爸听到孩子哭了
          他爸要去喂奶了
          她妈听到孩子哭了
          她妈跑路了

猜你喜欢

转载自blog.csdn.net/WestLonly/article/details/79943925