1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-25 22:46:05 +03:00
This commit is contained in:
lesheng 2020-08-18 09:22:50 +08:00
parent f978e42036
commit ecf1b0fb1d
30 changed files with 1855 additions and 1837 deletions

11
creational/factory.go Normal file
View File

@ -0,0 +1,11 @@
package creational
import "io"
// 工厂方法创建设计模式允许创建对象,而不必指定将要创建的对象的确切类型。
// 示例实现展示了如何使用不同的后端,如内存、磁盘存储。
// Store 对象类型
type Store interface {
Open(string) (io.ReadWriteCloser, error)
}

View File

@ -2,13 +2,16 @@
Factory method creational design pattern allows creating objects without having Factory method creational design pattern allows creating objects without having
to specify the exact type of the object that will be created. to specify the exact type of the object that will be created.
工厂方法创建型设计模式允许创建对象,不用指定要创建对象的类型。
## Implementation ## Implementation
The example implementation shows how to provide a data store with different The example implementation shows how to provide a data store with different
backends such as in-memory, disk storage. backends such as in-memory, disk storage.
示例实现展示了如何使用不同的后端,如内存、磁盘存储。
### Types ### Types(对象类型)
```go ```go
package data package data
@ -20,19 +23,21 @@ type Store interface {
} }
``` ```
### Different Implementations ### Different Implementations(不同实现)
```go ```go
package data package data
type StorageType int type StorageType int
// 类型实现对象枚举
const ( const (
DiskStorage StorageType = 1 << iota DiskStorage StorageType = 1 << iota
TempStorage TempStorage
MemoryStorage MemoryStorage
) )
// 工厂方法(实例化对象)
func NewStore(t StorageType) Store { func NewStore(t StorageType) Store {
switch t { switch t {
case MemoryStorage: case MemoryStorage:
@ -48,8 +53,10 @@ func NewStore(t StorageType) Store {
## Usage ## Usage
With the factory method, the user can specify the type of storage they want. With the factory method, the user can specify the type of storage they want.
使用工厂方法,指定实现类型枚举。
```go ```go
// 给工厂方法提供实现类型枚举
s, _ := data.NewStore(data.MemoryStorage) s, _ := data.NewStore(data.MemoryStorage)
f, _ := s.Open("file") f, _ := s.Open("file")