课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript 修饰模式

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

问题

你有一组数据,需要在多个过程、可能变换的方式下处理。

解决方案

使用修饰模式来构造如何更改应用。

  1. miniMarkdown = (line) ->
  2. if match = line.match /^(#+)\s*(.*)$/
  3. headerLevel = match[1].length
  4. headerText = match[2]
  5. "<h#{headerLevel}>#{headerText}</h#{headerLevel}>"
  6. else
  7. if line.length > 0
  8. "<p>#{line}</p>"
  9. else
  10. ''
  11. stripComments = (line) ->
  12. line.replace /\s*\/\/.*$/, '' # Removes one-line, double-slash C-style comments
  13. class TextProcessor
  14. constructor: (@processors) ->
  15. reducer: (existing, processor) ->
  16. if processor
  17. processor(existing or '')
  18. else
  19. existing
  20. processLine: (text) ->
  21. @processors.reduce @reducer, text
  22. processString: (text) ->
  23. (@processLine(line) for line in text.split("\n")).join("\n")
  24. exampleText = '''
  25. # A level 1 header
  26. A regular line
  27. // a comment
  28. ## A level 2 header
  29. A line // with a comment
  30. '''
  31. processor = new TextProcessor [stripComments, miniMarkdown]
  32. processor.processString exampleText
  33. # => "<h1>A level 1 header</h1>\n<p>A regular line</p>\n\n<h2>A level 2 header</h2>\n<p>A line</p>"

结果

  1. <h1>A level 1 header</h1>
  2. <p>A regular line</p>
  3. <h2>A level 1 header</h2>
  4. <p>A line</p>

讨论

TextProcessor 服务有修饰的作用,可将个人、专业文本处理器绑定在一起。这使 miniMarkdown 和 stripComments 组件只专注于处理一行文本。未来的开发人员只需要编写函数返回一个字符串,并将它添加到阵列的处理器即可。

我们甚至可以修改现有的修饰对象动态:

  1. smilies =
  2. ':)' : "smile"
  3. ':D' : "huge_grin"
  4. ':(' : "frown"
  5. ';)' : "wink"
  6. smilieExpander = (line) ->
  7. if line
  8. (line = line.replace symbol, "<img src='#{text}.png' alt='#{text}' />") for symbol, text of smilies
  9. line
  10. processor.processors.unshift smilieExpander
  11. processor.processString "# A header that makes you :) // you may even laugh"
  12. # => "<h1>A header that makes you <img src='smile.png' alt='smile' /></h1>"
  13. processor.processors.shift()
  14. # => "<h1>A header that makes you :)</h1>"
转载本站内容时,请务必注明来自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号