-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand_patern.rb
125 lines (99 loc) · 2.51 KB
/
command_patern.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
116
117
118
119
120
121
122
123
124
125
=begin
Команда (Command) — поведенческий шаблон проектирования, представляющий
действие. Объект команды инкапсулирует в себе само действие и его
параметры. Рассмотрим применение паттерна на примере работы с файлами.
Создадим 3 команды для создания, копирования и удаления файла.
Классы CreateFile, CopyFile, DeleteFile соответственно
=end
class BaseComand
attr_reader :description
def initialize(description)
@description = description
end
def execute
raise 'Method execute must be implemented!'
end
def unexecute
raise 'Method unexecute must be implemented!'
end
end
class CreateFile < BaseComand
def initialize(path, content)
super("Create file: #{path}")
@path = path
@content = content
end
def execute
f = File.open(@path, 'w')
f.write(@content)
f.close
end
def unexecute
File.delete(@path) if File.exist?(@path)
end
end
class CopyFile < BaseComand
require 'fileutils'
def initialize(source, target)
super("Copy file: #{source} to #{target}")
@source = source
@target = target
end
def execute
if File.exists?(@target)
@content = File.read(@target)
end
FileUtils.copy(@source, @target)
end
def unexecute
if !@content.nil?
f = File.open(@target, 'w')
f.write(@content)
f.close
else
File.delete(@target)
end
end
end
class DeleteFile < BaseComand
def initialize(path)
super("Delete file: #{path}")
@path = path
end
def execute
if File.exists?(@path)
@content = File.read(@path)
File.delete(@path)
end
end
def unexecute
return if @content.empty?
f = File.open(@path, 'w')
f.write(@content)
f.close
end
end
class CompositeCommand
def initialize
@commands = []
end
def add_command(command)
@commands << command
end
def up
@commands.each { |cmd| cmd.execute }
end
def down
@commands.reverse.each { |cmd| cmd.unexecute }
end
def description
@commands.inject([]){ |result, cmd| result << cmd.description }.join(' -> ')
end
end
cmds = CompositeCommand.new
cmds.add_command(CreateFile.new('file1.txt', "Hello world\n"))
cmds.add_command(CopyFile.new('file1.txt', 'file2.txt'))
cmds.add_command(DeleteFile.new('file1.txt'))
cmds.up
p cmds.description
#cmds.down