Last active
December 13, 2015 19:48
-
-
Save foo9/4965265 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 命令を受けて処理を実行する | |
class Receiver | |
up: -> | |
console.log "up" | |
down: -> | |
console.log "down" | |
right: -> | |
console.log "right" | |
left: -> | |
console.log "left" | |
# 命令のインターフェイスを定義 | |
class Command | |
constructor: (@receiver) -> | |
action: -> | |
# 実際の処理はoverrideして書く | |
# 実際の命令(上) | |
class UpCommand extends Command | |
constructor: (@receiver) -> | |
super @receiver | |
# override | |
action: -> | |
receiver.up() | |
# 実際の命令(下) | |
class DownCommand extends Command | |
constructor: (@receiver) -> | |
super @receiver | |
# override | |
action: -> | |
receiver.down() | |
# 実際の命令(右) | |
class RightCommand extends Command | |
constructor: (@receiver) -> | |
super @receiver | |
# override | |
action: -> | |
receiver.right() | |
# 実際の命令(左) | |
class LeftCommand extends Command | |
constructor: (@receiver) -> | |
super @receiver | |
# override | |
action: -> | |
receiver.left() | |
# 保持している命令を実行する | |
class Invoker | |
commands: [] | |
addCommand: (cmd) -> | |
@commands.push cmd | |
addCommands: (cmds) -> | |
@commands = @commands.concat cmds | |
reverse: -> | |
@commands = @commands.reverse() | |
execute: -> | |
cmd = @commands.shift() | |
if cmd? | |
cmd.action() | |
return true | |
else | |
return false | |
executeAll: -> | |
cmd.action() for cmd in @commands | |
# 使用例 | |
receiver = new Receiver() | |
invoker = new Invoker() | |
invoker.addCommand(new LeftCommand(receiver)) | |
invoker.addCommand(new RightCommand(receiver)) | |
invoker.addCommand(new UpCommand(receiver)) | |
invoker.addCommand(new DownCommand(receiver)) | |
invoker.executeAll() # left, right, up, down |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment