CoffeeScript 修饰模式


本文整理自网络,侵删。

修饰模式

问题

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

解决方案

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

miniMarkdown = (line) ->
    if match = line.match /^(#+)\s*(.*)$/
        headerLevel = match[1].length
        headerText = match[2]
        "<h#{headerLevel}>#{headerText}</h#{headerLevel}>"
    else
        if line.length > 0
            "<p>#{line}</p>"
        else
            ''

stripComments = (line) ->
    line.replace /\s*\/\/.*$/, '' # Removes one-line, double-slash C-style comments

class TextProcessor
    constructor: (@processors) ->

    reducer: (existing, processor) ->
        if processor
            processor(existing or '')
        else
            existing
    processLine: (text) ->
        @processors.reduce @reducer, text
    processString: (text) ->
        (@processLine(line) for line in text.split("\n")).join("\n")

exampleText = '''
              # A level 1 header
              A regular line
              // a comment
              ## A level 2 header
              A line // with a comment
              '''

processor = new TextProcessor [stripComments, miniMarkdown]

processor.processString exampleText

# => "<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>"

结果

<h1>A level 1 header</h1>
<p>A regular line</p>

<h2>A level 1 header</h2>
<p>A line</p>

讨论

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

阅读剩余部分

相关阅读 >>

CoffeeScript 计算(美国和加拿大的)感恩节日期

CoffeeScript 筛选数组

CoffeeScript 将数组连接

CoffeeScript 找到上一个月(或下一个月)

CoffeeScript 修饰模式

CoffeeScript 类的混合

CoffeeScript 桥接模式

CoffeeScript 服务端和客户端的代码重用

CoffeeScript 生成随机数

CoffeeScript 计算月球的相位

更多相关阅读请进入《CoffeeScript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...