-
Notifications
You must be signed in to change notification settings - Fork 1
/
Decorator.rb
79 lines (57 loc) · 1.4 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
=begin
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
The benefits of this implementation are:
can be wrapped infinitely using Ruby instantiation
delegates through all decorators
can use same decorator more than once on component
The drawbacks of this implementation are:
cannot transparently use component’s original interface
The problems with inheritance include:
Choices are made statically.
Clients can’t control how and when to decorate a component.
Tight coupling.
Changing the internals of the superclass means all subclasses must change.
In Ruby, including a module is also inheritance:
https://github.com/nslocum/design-patterns-in-ruby
=end
class Coffee
def cost
2
end
end
module Milk
def cost
super + 0.4
end
end
module Sugar
def cost
super + 0.2
end
end
coffee = Coffee.new
coffee.extend(Milk)
coffee.extend(Sugar)
coffee.cost # 2.6
#The “Plain Old Ruby Object” (PORO) decorator
class Coffee
def cost
2
end
def origin
"Colombia"
end
end
class Milk
def initialize(component)
@component = component
end
def cost
@component.cost + 0.4
end
end
coffee = Coffee.new
Sugar.new(Milk.new(coffee)).cost # 2.6
Sugar.new(Sugar.new(coffee)).cost # 2.4
Sugar.new(Milk.new(coffee)).class # Sugar
Milk.new(coffee).origin # NoMethodError