CoffeeScript 修饰模式

🌙
手机阅读
本文目录结构

修饰模式

问题

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

解决方案

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

  1. miniMarkdown = (line) ->
  2. if match = line.match /^(#+)\s*(.*)$/
  3. headerLevel = match[1].length
  4. headerText = match[2]
  5. "#{headerText}"
  6. else
  7. if line.length > 0
  8. "#{line}"
  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. # => "A level 1 header\nA regular line\n\nA level 2 header\nA line"

结果

  1. A level 1 header
  2. A regular line
  3. A level 1 header
  4. A line

讨论

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, "") 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. # => "A header that makes you "
  13. processor.processors.shift()
  14. # => "A header that makes you :)"

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了