-

命令模式

问题

你需要让另一个对象处理你自己的可执行的代码。

解决方案

使用Command pattern传递函数的引用。

# Using a private variable to simulate external scripts or modules
incrementers = (() ->
    privateVar = 0

    singleIncrementer = () ->
        privateVar += 1

    doubleIncrementer = () ->
        privateVar += 2

    commands = 
        single: singleIncrementer
        double: doubleIncrementer
        value: -> privateVar
)()

class RunsAll
    constructor: (@commands...) ->
    run: -> command() for command in @commands

runner = new RunsAll(incrementers.single, incrementers.double, incrementers.single, incrementers.double)
runner.run()
incrementers.value() # => 6

讨论

以函数作为一级的对象且从Javascript函数的变量范围中继承,CoffeeScript使语言模式几乎看不出来。事实上,任何函数传递回调函数可以作为一个命令

jqXHR对象返回jQuery AJAX方法使用此模式。

jqxhr = $.ajax
    url: "/"

logMessages = ""

jqxhr.success -> logMessages += "Success!\n"
jqxhr.error -> logMessages += "Error!\n"
jqxhr.complete -> logMessages += "Completed!\n"

# On a valid AJAX request:
# logMessages == "Success!\nCompleted!\n"