forked from AlexanderGrom/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory_method.go
74 lines (60 loc) · 1.5 KB
/
factory_method.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
71
72
73
74
// Package factory_method is an example of the Factory Method Pattern.
package factory_method
import (
"log"
)
// Creater provides a factory interface.
type Creater interface {
CreateProduct(action string) Producter // Factory Method
}
// Producter provides a product interface.
// All products returned by factory must provide a single interface.
type Producter interface {
Use() string // Every product should be can be used
}
// ConcreteCreater implements Creater interface.
type ConcreteCreater struct {
}
// NewCreater is the ConcreteCreater constructor.
func NewCreater() Creater {
return &ConcreteCreater{}
}
// CreateProduct is a Factory Method
func (p *ConcreteCreater) CreateProduct(action string) Producter {
var product Producter
switch action {
case "A":
product = &ConcreteProductA{action}
case "B":
product = &ConcreteProductB{action}
case "C":
product = &ConcreteProductC{action}
default:
log.Fatalln("Unknown Action")
}
return product
}
// ConcreteProductA implements product "A"
type ConcreteProductA struct {
action string
}
// Use returns product action
func (p *ConcreteProductA) Use() string {
return p.action
}
// ConcreteProductB implements product "B"
type ConcreteProductB struct {
action string
}
// Use returns product action
func (p *ConcreteProductB) Use() string {
return p.action
}
// ConcreteProductC implements product "C"
type ConcreteProductC struct {
action string
}
// Use returns product action
func (p *ConcreteProductC) Use() string {
return p.action
}