-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathfactory_method.go
82 lines (66 loc) · 1.64 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
75
76
77
78
79
80
81
82
// Package factory_method is an example of the Factory Method pattern.
package factory_method
import (
"log"
)
// action helps clients to find out available actions.
type action string
const (
A action = "A"
B action = "B"
C action = "C"
)
// Creator provides a factory interface.
type Creator interface {
CreateProduct(action action) Product // Factory Method
}
// Product provides a product interface.
// All products returned by factory must provide a single interface.
type Product interface {
Use() string // Every product should be usable
}
// ConcreteCreator implements Creator interface.
type ConcreteCreator struct{}
// NewCreator is the ConcreteCreator constructor.
func NewCreator() Creator {
return &ConcreteCreator{}
}
// CreateProduct is a Factory Method.
func (p *ConcreteCreator) CreateProduct(action action) Product {
var product Product
switch action {
case A:
product = &ConcreteProductA{string(action)}
case B:
product = &ConcreteProductB{string(action)}
case C:
product = &ConcreteProductC{string(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
}