课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript 适配器模式

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

想象你去国外旅行,一旦你意识到你的电源线插座与酒店房间墙上的插座不兼容时,幸运的是你记得带你的电源适配器。它将一边连接你的电源线插座另一边连接墙壁插座,允许它们之间进行通信。

同样的情况也可能会出现在代码中,当两个 ( 或更多 ) 实例 ( 类、模块等 ) 想跟对方通信,但其通信协议 ( 例如,他们所使用的语言交流 ) 不同。在这种情况下,Adapter 模式更方便。它会充当翻译,从一边到另一边。

解决方案

  1. # a fragment of 3-rd party grid component
  2. class AwesomeGrid
  3. constructor: (@datasource)->
  4. @sort_order = 'ASC'
  5. @sorter = new NullSorter # in this place we use NullObject pattern (another useful pattern)
  6. setCustomSorter: (@customSorter) ->
  7. @sorter = customSorter
  8. sort: () ->
  9. @datasource = @sorter.sort @datasource, @sort_order
  10. # don't forget to change sort order
  11. class NullSorter
  12. sort: (data, order) -> # do nothing; it is just a stub
  13. class RandomSorter
  14. sort: (data)->
  15. for i in [data.length-1..1] #let's shuffle the data a bit
  16. j = Math.floor Math.random() * (i + 1)
  17. [data[i], data[j]] = [data[j], data[i]]
  18. return data
  19. class RandomSorterAdapter
  20. constructor: (@sorter) ->
  21. sort: (data, order) ->
  22. @sorter.sort data
  23. agrid = new AwesomeGrid ['a','b','c','d','e','f']
  24. agrid.setCustomSorter new RandomSorterAdapter(new RandomSorter)
  25. agrid.sort() # sort data with custom sorter through adapter

讨论

当你要组织两个具有不同接口的对象之间的交互时,适配器是有用的。它可以当你使用第三方库或者使用遗留代码时使用。在任何情况下小心使用适配器:它可以是有用的,但它也可以导致设计错误。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号