1. Factory Method Pattern

Factory method creational design pattern allows creating objects without having to specify the exact type of the object that will be created.

1.1. Implementation

The example implementation shows how to provide a data store with different backends such as in-memory, disk storage.

1.1.1. Types

package data

import "io"

type Store interface {
    Open(string) (io.ReadWriteCloser, error)
}

1.1.2. 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( /*...*/ )
    }
}

1.2. Usage

With the factory method, the user can specify the type of storage they want.

s, _ := data.NewStore(data.MemoryStorage)
f, _ := s.Open("file")

n, _ := f.Write([]byte("data"))
defer f.Close()
Copyright © studygolang.com 2013 all right reserved,powered by Gitbook该文件修订时间: 2017-07-21 20:12:22

results matching ""

    No results matching ""