js 设计模式 第八章 Bridge Pattern
来源:互联网 发布:买了淘宝模板怎么修改 编辑:程序博客网 时间:2024/05/13 21:59
场景 1 事件处理
是页面上,我们往往用到事件绑定。这这个例子中,我们对元素添加click 事件处理,在handle 函数中,通过得到元素的id属性,进行ajax操作。
addEvent(element, 'click', getBeerById);function getBeerById(e) { var id = this.id; asyncRequest('GET', 'beer.uri?id=' + id, function(resp) { // Callback response. console.log('Requested Beer: ' + resp.responseText); });}
这个绑定函数有几个问题:
- 因为改函数需要e这个事件变量,所以这个函数只能运行在浏览器的环境中,这样不能简单的测试这个函数的正确性
- 这个函数的输入参数是e,而里面的实现根本就不需要这个变量
一个更好的方法是,写一个独立的函数
function getBeerById(id, callback) { // Make request for beer by ID, then return the beer data. asyncRequest('GET', 'beer.uri?id=' + id, function(resp) { // callback response callback(resp.responseText); });}好处:
- 函数的输入参数是id,更符合逻辑
- callback 方法更通用。任何充服务器取得的数据,通过callback得到,并进行下一步的处理。
- program to interface ,not an implementation
- 可以在单元测试中测试
最后,上面的事件绑定实现方式如下:
addEvent(element, 'click', getBeerByIdBridge);function getBeerByIdBridge (e) { getBeerById(this.id, function(beer) { console.log('Requested Beer: '+beer); });}有了这个桥接函数,我们就可以在任何地方测试getBeerById这个核心函数
场景2 类的私有属性
通过类的特权方法,访问类的私有属性,这个特权方法,就是私有属性通向外边的桥
var Public = function() {var secret = 3;this.privilegedGetter = function() { return secret;};};var o = new Public;var data = o.privilegedGetter();
xiong:已为接口编程,而非实现编程为指导,通过桥来链接抽象的接口和实现。
- js 设计模式 第八章 Bridge Pattern
- 设计模式之Bridge Pattern
- 设计模式之Bridge Pattern
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式--桥接模式(bridge pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式-桥接模式(Bridge Pattern)
- 设计模式 桥接模式(Bridge Pattern)
- 设计模式-----桥接模式(Bridge Pattern)
- 设计模式之桥梁模式--- Pattern Bridge
- 去求1000以内偶数的和
- Flex坐标系统及转换
- switch选择方法实例—数字转换成中文大写
- js不报异常信息
- 图像处理(四)图像缩放
- js 设计模式 第八章 Bridge Pattern
- 流媒体服务器 架设
- 黑马程序员之ASP.NET学习笔记:TREEVIEW中动态增加结点
- 表维护中,怎样把数据下载到本地?
- poj 2752 Seek the Name, Seek the Fame
- 关闭js弹出窗体时,可能会弹出警告
- Android SlidingDrawer 滑动抽屉效果
- OpenGL 4.3 (Core Profile) - August 6, 2012 spec Fundamental 2.3 Command Execution
- AIX/Unix/Linux/HP-UX 系统中文字符集