工厂模式--Factory Method with Go

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值