-
Notifications
You must be signed in to change notification settings - Fork 2
/
factory_method.go
67 lines (51 loc) · 971 Bytes
/
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
package main
import (
"fmt"
)
/*
A factory method gives you an implmentation of an interface. Usually the input is a
constant. Sometimes constructed objects are reused instead of re-instantiated.
*/
const (
SportsCar = 1 << iota
FamilyCar
Truck
)
func main() {
var car Car
car, _ = FactoryMethod(SportsCar)
car.Drive()
car, _ = FactoryMethod(FamilyCar)
car.Drive()
car, _ = FactoryMethod(Truck)
car.Drive()
}
type Car interface {
Drive()
}
func FactoryMethod(carType int) (Car, error) {
switch carType {
case SportsCar:
return Tesla{}, nil
case FamilyCar:
return Honda{}, nil
case Truck:
return Uhaul{}, nil
}
return nil, fmt.Errorf("car not found!")
}
type Tesla struct {
}
func (t Tesla) Drive() {
fmt.Println("Driving a hella fast Tesla")
}
type Uhaul struct {
}
func (u Uhaul) Drive() {
fmt.Println("Moving stuff in my Uhaul")
}
type Honda struct {
}
func (h Honda) Drive() {
fmt.Println("Taking the family on a drive")
}