-
Notifications
You must be signed in to change notification settings - Fork 105
/
decorator.rb
62 lines (53 loc) · 1.1 KB
/
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
58
59
60
61
62
# Attach additional responsibilities to an object dynamically. Decorators
# provide a flexible alternative to subclassing for extending functionality
class ItemDecorator
def initialize(item)
@item = item
end
# this needs to be delegated with other efective way
def use
@item.use
end
end
class MagicItemDecorator < ItemDecorator
def price
@item.price * 3
end
def description
@item.description + "Magic"
end
end
class MasterpieceItemDecorator < ItemDecorator
def price
@item.price * 2
end
def description
@item.description + "Masterpiece"
end
end
class Item
attr_reader :price, :description
def initialize
@price = 10
@description = "Item "
end
def use
"do something"
end
end
# Usage
item = Item.new
magic_item = MagicItemDecorator.new(item)
puts magic_item.price
# => 30
puts magic_item.description
# => Item Magic
masterpiece_item = MasterpieceItemDecorator.new(item)
puts masterpiece_item.price
# => 20
puts masterpiece_item.description
# => Item Masterpiece
# all next lines puts "do something"
item.use
magic_item.use
masterpiece_item.use