Factory method creational design pattern allows creating objects without having to specify the exact type of the object that will be created.
工厂方法创建型设计模式允许创建对象,而不必指定要创建的对象的确切类型。
Implementation
The example implementation shows how to provide a data store with different backends such as in-memory, disk storage.
例如实现显示如何提供数据存储与不同的后端如内存、磁盘存储。
Types1
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
28package data
import "io"
type Store interface {
Open(string) (io.ReadWriteCloser, error)
}
// Different Implementations
package data
type StorageType int
const (
DiskStorage StorageType = 1 << iota
TempStorage
MemoryStorage
)
func NewStore(t StorageType) Store {
switch t {
case MemoryStorage:
return newMemoryStorage( /*...*/ )
case DiskStorage:
return newDiskStorage( /*...*/ )
default:
return newTempStorage( /*...*/ )
}
}
Usage
With the factory method, the user can specify the type of storage they want.
使用工厂方法,用户可以指定他们想要的存储类型。
1 | s, _ := data.NewStore(data.MemoryStorage) |