File tree 2 files changed +59
-1
lines changed
2 files changed +59
-1
lines changed Original file line number Diff line number Diff line change @@ -17,7 +17,7 @@ A curated collection of idiomatic design & application patterns for Go language.
17
17
| :-------:| :----------- | :------:|
18
18
| [ Abstract Factory] ( /creational/abstract_factory.md ) | Provides an interface for creating families of releated objects | ✘ |
19
19
| [ 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 | ✔ |
21
21
| [ Object Pool] ( /creational/object-pool.md ) | Instantiates and maintains a group of objects instances of the same type | ✔ |
22
22
| [ Singleton] ( /creational/singleton.md ) | Restricts instantiation of a type to one object | ✔ |
23
23
Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments