【JS 设计模式 】观察者模式之实时改变页面中的金额数

来源:互联网 发布:关闭139和445端口 编辑:程序博客网 时间:2024/06/06 09:32

观察者设计模式概念:

有时被称作发布/订阅模式,观察者模式定义了一种一对多的依赖关系,让多个观察者(每个处的主账号金额函数)对象同时监听某一个主题对象(修改子账号金额后调用的deliver的对象Publisher)。这个主题对象在状态(调用deliver方法)发生变化时,会通知所有观察者对象,使它们能够自动更新自己。


在一个会员管理系统中,主账号给子账号充值金额的功能。
场景:主账号有10000元,如果给子账号充值增加1000元,那么主账号的金额应该相对应报减少1000元显示9000元;

页面上有多种处需要实时改变的位置,怎么办?


在上图中有三处总余额要显示;

通过子加减按钮来调整账号余额的话,这三处的总余额也需要相对改变;


第一种方式:在一个函数中加添加多个元素对象,这样可以是一个门面模式,来简化调用重复的代码;

function modifyPrice(price) {  $("#a1").html(price);  $("#a2").html(price);  $("#a3").html(price);  $("#a4").html(price);}


第二种方式:用观察者设计模式,如果状态改变了和它相关的依赖也会随之变化;
// 订阅者function a1( price ) {  console.log( price );  $("#a1").html(price);}// 订阅者function a2( price ) {  console.log( price );  $("#a2").html(price);}// 订阅者function a3( price ) {  console.log( price );  $("#a3").html(price);}// 订阅者function a4( price ) {  console.log( price );  $("#a4").html(price);}// 发布者function PublisherPrice() {  this.subscribers = [];  this.addSubscriber = function( subscriber) {    // some  如果返回true说明this.subscriber数姐中已经有了相同的订阅者了,当遇到第一个比较值是true就返回true,如果没有遇到true最后返回一个false;    var isExsit = this.subscribers.some(function( el ){      return el == subscriber    });    if ( !isExsit ) {      this.subscribers.push( subscriber );    }    return this;  }  this.deliver = function(     // forEach 相当于是for循环    this.subscribers.forEach(function( fn ) {      fn(price);    });    return this;  }}


客户端调用

var publisherPrice = new PublisherPrice();publisherPrice.addSubscriber(a1);publisherPrice.addSubscriber(a2);publisherPrice.addSubscriber(a3);publisherPrice.addSubscriber(a4);publisherPrice.deliver("¥200.00");


第二种有什么优点?
1、每一个订阅者都是相互独立的只和发布者有关系,与发布者是一对多的关系,也可以是一对一的关系。
2、每一个订阅者可以根据自己的需求来调用,而不影响其它订阅者
2、与第一种方式相比,第二种方式的代码可读性、可维护性强;


1 0