当前位置:K88软件开发文章中心编程语言JavaScriptCoffeeScript → 文章内容

CoffeeScript 修饰模式

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 15:34:14

由 珍珍阿姨 创建,Carrie 最后一次修改 2016-08-12 修饰模式问题你有一组数据,需要在多个过程、可能变换的方式下处理。解决方案使用修饰模式来构造如何更改应用。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 commentsclass 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组件只专注于处理一行文本。未来的开发人员只需要编写函数返回一个字符串,并将它添加到阵列的处理器即可。我们甚至可以修改现有的修饰对象动态:smilies = ':)' : "smile" ':D' : "huge_grin" ':(' : "frown" ';)' : "wink"smilieExpander = (line) -> if line (line = line.replace symbol, "<img src=https://www.w3cschool.cn/coffeescript/'#{text}.png' alt='#{text}' />") for symbol, text of smilies lineprocessor.processors.unshift smilieExpanderprocessor.processString "# A header that makes you :) // you may even laugh"# => "<h1>A header that makes you <img src=https://www.w3cschool.cn/coffeescript/'smile.png' alt='smile' /></h1>"processor.processors.shift()# => "<h1>A header that makes you :)</h1>"

CoffeeScript 修饰模式