-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathdecorator.rb
57 lines (45 loc) · 975 Bytes
/
decorator.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
# The decorator design pattern allows for features to be added dynamically to an
# existing object.
class Decorator
def initialize(item)
@item = item
end
def use
item.use
end
# Dynamic method that added in decorator
def another_use
item.use + 'another way'
end
end
class MagicDecorator < Decorator
def description
@item.description + 'Magic'
end
end
class MasterpieceDecorator < Decorator
def description
@item.description + 'Masterpiece'
end
end
# Class what should be decorated
class Item
attr_reader :description
def initialize
@description = 'Item '
end
def use
'use it'
end
end
# Usage
item = Item.new
puts item.description # => Item
magic_item = MagicDecorator.new(item)
puts magic_item.description # => Item Magic
masterpiece_item = MasterpieceDecorator.new(item)
puts masterpiece_item.description # => Item Masterpiece
# All next lines puts "use it"
item.use
magic_item.use
masterpiece_item.use