当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript设计模式--桥梁模式引入操作实例分析

JavaScript设计模式--桥梁模式引入操作实例分析

2020年06月23日  | 移动技术网IT编程  | 我要评论

本文实例讲述了javascript设计模式--桥梁模式引入操作。分享给大家供大家参考,具体如下:

1.使用情况

(1)事件的监控

#1,利用页面的button来选择宠物的例子(思路)

button.addevent(element,"click",getpetbybame);
  function getpetbybame(e){
    var id = this.id;
    asyncrquest("get",'pet.action?id='+id,function(pet){
      consols.log("request pet"+pet.resopnsetext)
    })
  }

#2,addevent函数

/*obj:需要增加事件的对象
* type:事件名称
* fn:执行事件的函数
* */
function addevent(obj,type,fn){//addevent:为某个文档节点增加事件的方法
  if(obj.addeventlistener){//mozilla中:
    obj.addeventlistener(type,fn,false);
  }else if(obj.attachevent){//ie中:
    obj["e"+type+fn] = fn;
    obj[type+fn] = function(){
      obj["e"+type+fn]()
    }
    obj.attachevent("on"+type,fn)
  }
}

总结:该种方式对于单元测试很难进行

改进为用简单的桥梁模式来解决

#1,后台中的api

function getpetbybame(id,callback){
    sayncrquest("get",'url?id='+id,function(pet){
      callback(pet)
    })

#2,桥梁

//定义一个桥梁叫抽象和实现相互联系在一起
  addevent(element,"click",getpetbynamebridge)
  function getpetbynamebridge(){
    getpetbybame(this.id,function(pet){
      consols.log("request pet"+pet.resopnsetext);
    })
  }

总结:这种做法使api和展现层完全分离,api和展现层可以灵活的变动。

(2)特权函数

//特权函数
var privilege=function () {
  //信息全封闭,内部业务逻辑复杂,做成一个特权函数,使调用方便
  var complex=function (x,y) {
    //复杂的数学处理
  }

 this.bridge=function () { //提供公共接口,返回一个单体
   return {
     bridgeadd:function () {
       //处理前
       complex(1,2);
       //处理后
     }

   }
 }
}

(3)多个类的连接

//多个类的连接
var class1=function (a,b) {
  this.a=a;
  this.b=b;
}
  var class2=function (e) {
    this.e=e;
  }
  //桥梁的连接
  var bridgeclass=function () {
    this.one=new class1(1,2);
    this.two=new class1(1);
  }
//目的:两个类能独立的修改,而门面的意义在于调用方便

桥梁模式:

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网