Skip to content

Commit 4595241

Browse files
committed
creational/factory: implement factory method pattern
1 parent c851ce7 commit 4595241

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ A curated collection of idiomatic design & application patterns for Go language.
1717
|:-------:|:----------- |:------:|
1818
| [Abstract Factory](/creational/abstract_factory.md) | Provides an interface for creating families of releated objects ||
1919
| [Builder](/creational/builder.md) | Builds a complex object using simple objects ||
20-
| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | |
20+
| [Factory Method](/creational/factory.md) | Defers instantiation of an object to a specialized function for creating instances | |
2121
| [Object Pool](/creational/object-pool.md) | Instantiates and maintains a group of objects instances of the same type ||
2222
| [Singleton](/creational/singleton.md) | Restricts instantiation of a type to one object ||
2323

creational/factory.md

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Factory Method Pattern
2+
3+
Factory method creational design pattern allows creating objects without having
4+
to specify the exact type of the object that will be created.
5+
6+
## Implementation
7+
8+
The example implementation shows how to provide a data store with different
9+
backends such as in-memory, disk storage.
10+
11+
### Types
12+
13+
```go
14+
package data
15+
16+
import "io"
17+
18+
type Store interface {
19+
Open(string) (io.ReadWriteCloser, error)
20+
}
21+
```
22+
23+
### Different Implementations
24+
25+
```go
26+
package data
27+
28+
type StorageType int
29+
30+
const (
31+
DiskStorage StorageType = 1 << iota
32+
TempStorage
33+
MemoryStorage
34+
)
35+
36+
func NewStore(t StorageType) Store {
37+
switch t {
38+
case MemoryStorage:
39+
return newMemoryStorage( /*...*/ )
40+
case DiskStorage:
41+
return newDiskStorage( /*...*/ )
42+
default:
43+
return newTempStorage( /*...*/ )
44+
}
45+
}
46+
```
47+
48+
## Usage
49+
50+
With the factory method, the user can specify the type of storage they want.
51+
52+
```go
53+
s, _ := data.NewStore(data.MemoryStorage)
54+
f, _ := s.Open("file")
55+
56+
n, _ := f.Write([]byte("data"))
57+
defer f.Close()
58+
```

0 commit comments

Comments
 (0)