/*
Factory Method: 工厂设计模式允许创建对象,而无需指定将要创建的对象的确切类型。
Implementation:
举个栗子: 用个例子展示怎么把数据存储在不同的后端,比如:内存、磁盘
Types: type 一个Store , interface类型
Usage: 用户可以根据不同的类型通过工厂创建不同的对象
*/
package main
import (
"fmt"
"io"
)
// Types , define a method Open(string),and return (io.ReadWriterCloser ,error)
type Store interface {
Open(string) (io.ReadWriteCloser, error)
}
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()
}
}
func newDiskStorage() Store {
fmt.Println("create newDiskStorage object ...")
return nil
}
func newMemoryStorage() Store {
fmt.Println("create newMemoryStorage object ...")
return nil
}
func newTempStorage() Store {
fmt.Println("create newTempStorage object ...")
return nil
}
//Usage : example
func Usage_main() {
//chose one store type
s := NewStore(MemoryStorage)
//open file
f, _ := s.Open("file")
_, err := f.Write([]byte("data"))
fmt.Print(err)
//延迟关闭文件
defer f.Close()
}
/*
简单工厂模式
*/
type Operator interface {
Operate(int, int) int
}
type AddOperation struct{}
func (add *AddOperation) Operate(x, y int) int {
return x + y
}
type SubOperation struct {
}
func (sub SubOperation) Operate(x, y int) int {
return x - y
}
//建立一个工厂
type CreateFactory struct {
}
func NewFactory() *CreateFactory {
return &CreateFactory{}
}
func (cf *CreateFactory) Op(opName string) Operator {
switch opName {
case "+":
return &AddOperation{}
case "-":
return &SubOperation{}
default:
fmt.Println("Input Error ")
return nil
}
}
/*
工厂方法模式
*/
type Operation struct {
a float64
b float64
}
type Operational interface {
GetResult() float64
SetA(float64)
SetB(float64)
}
func (op* Operation) SetA(a float64){
op.a = a
}
func (op* Operation) SetB(b float64){
op.b = b
}
type AddOp struct {
Operation
}
type SubOp struct {
Operation
}
func (add *AddOp) GetResult() float64{
return add.a+add.b
}
func (sub *SubOp) GetResult() float64{
return sub.a-sub.b
}
type IFactory interface {
CtOp() Operation
}
type AddFac struct {
}
func (this *AddFac) CtOp() Operational{
return &(AddOp{})
}
type SubFac struct {
}
func (sub *SubFac) CtOp() Operational{
return &SubOp{}
}
func main() {
fac:=&AddFac{}
oper:=fac.CtOp()
oper.SetB(5)
oper.SetA(4)
fmt.Println("result: ",oper.GetResult())
}