-
Notifications
You must be signed in to change notification settings - Fork 13
/
06_command_sample.rb
115 lines (96 loc) · 2.22 KB
/
06_command_sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
require "fileutils"
# コマンドのインターフェース
class Command
attr_reader :description
def initialize(description)
@description = description
end
def execute
end
end
# ファイルを作成する命令
class CreateFile < Command
def initialize(path, contents)
super("Create file : #{path}")
@path = path
@contents = contents
end
def execute
f = File.open(@path, "w")
f.write(@contents)
f.close
end
def undo_execute
File.delete(@path)
end
end
# ファイルを削除する命令
class DeleteFile < Command
def initialize(path)
super("Delete file : #{path}")
@path = path
end
def execute
if File.exists?(@path)
@content = File.read(@path)
end
File.delete(@path)
end
def undo_execute
f = File.open(@path, "w")
f.write(@contents)
f.close
end
end
# ファイルをコピーする命令
class CopyFile < Command
def initialize(source, target)
super("Copy file : #{source} to #{target}")
@source = source
@target = target
end
def execute
FileUtils.copy(@source, @target)
end
def undo_execute
File.delete(@target)
if(@contents)
f = File.open(@target, "w")
f.write(@contents)
f.close
end
end
end
# 複数のコマンドをまとめて実行できるようにしたオブジェクト
class CompositeCommand < Command
def initialize
@commands = []
end
def add_command(cmd)
@commands << cmd
end
def execute
@commands.each { |cmd| cmd.execute }
end
def undo_execute
@commands.reverse.each { |cmd| cmd.undo_execute }
end
def description
description = ""
@commands.each { |cmd| description += cmd.description + "\n"}
description
end
end
# ===========================================
command_list = CompositeCommand.new
command_list.add_command(CreateFile.new("file1.txt", "hello world\n"))
command_list.add_command(CopyFile.new("file1.txt", "file2.txt"))
command_list.add_command(DeleteFile.new("file1.txt"))
command_list.execute
puts(command_list.description)
#=> Create file : file1.txt
#=> Copy file : file1.txt to file2.txt
#=> Delete file : file1.txt
# 処理を取り消すコマンド
command_list.undo_execute
# file2が消えている