-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
70 lines (54 loc) · 1.55 KB
/
wrapper.go
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
package structural
/*
Summary:
Add new functionality to objects dynamically by wrapping
the core objects inside a wrapper
Example:
Interface: Pizza
And many implementations but of 2 categories of implementation
1st: we create pizza type like peperroni and margaritta which gives the base pizza price "return 299"
2nd: then we add toppings on its base using wrapped structs on it which also implements Pizza interface "t.pizza.Price() + 20"
so that they can again be wrapped.
Benefit:
Using wrapper we can wrap objects countless number of times as
wrapper objects follow the same interface. Resulting objects gets a stacking
behaviour of all objects
Ref: https://refactoring.guru/design-patterns/decorator/go/example
*/
type Topping int
const (
Cheese Topping = iota
Chicken
)
// Pizza defines what makes a Pizza, this is the core
type Pizza interface {
Price() int
}
// Margaritta wraps the Pizza interface, it is an actual pizza implementation
type Margaritta struct {
pizza Pizza
}
func (t *Margaritta) Price() int {
return 300
}
// Pepperoni wraps the Pizza interface, it is an actual pizza implementation
type Pepperoni struct {
pizza Pizza
}
func (t *Pepperoni) Price() int {
return 400
}
// ToppingCheese wraps the Pizza interface, extends pizza functionality
type ToppingCheese struct {
pizza Pizza
}
func (t *ToppingCheese) Price() int {
return t.pizza.Price() + 30
}
// ToppingChicken wraps the Pizza interface, extends pizza functionality
type ToppingChicken struct {
pizza Pizza
}
func (t *ToppingChicken) Price() int {
return t.pizza.Price() + 40
}