go语言工厂模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/YYtomorrow/article/details/80360932
简单工厂 

简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。

package main
import "fmt"
type Factory interface {
    getResult(a, b int)
}
type Add struct{}
func (p *Add) getResult(a, b int) {
    fmt.Println(a + b)
}
type Mult struct{}
func (p *Mult) getResult(a, b int) {
    fmt.Println(a * b)
}
func CreateFactory(operatename string) Factory {
    switch operatename {
    case "+":
        return &Add{}
    case "*":
        return &Mult{}
    }
}
func main() {
    CreateFactory("+").getResult(1, 2)
    CreateFactory("*").getResult(1, 2)
}
工厂方法 

工厂方法是针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。 

在同一等级结构中,支持增加任意产品。

package main
import "fmt"
type OperationI interface {
    GetResult() float64
    SetA(float64)
    SetB(float64)
}
type Add struct {
    a float64
    b float64
}
func (p *Add) SetA(a float64) {
    p.a = a
}
func (p *Add) SetB(b float64) {
    p.b = b
}
func (p *Add) GetResult() float64 {
    return p.a + p.b
}
//加法工厂
type AddFactory struct{}
func (f AddFactory) CreateFactory() OperationI {
    return &Add{}
}
type Mult struct {
    a float64
    b float64
}
func (p *Mult) SetA(a float64) {
    p.a = a
}
func (p *Mult) SetB(b float64) {
    p.b = b
}
func (p *Mult) GetResult() float64 {
    return p.a * p.b
}
//乘法工厂
type MultFactory struct{}
func (f MultFactory) CreateFactory() OperationI {
    return &Mult{}
}
func main() {
    //创建工厂
    f := AddFactory{}
    //生产模型
    oper := f.CreateFactory()
    //对模型加工
    oper.SetA(1)
    oper.SetB(2)
    //生产完成
    fmt.Println(oper.GetResult())
    m := MultFactory{}
    oper = m.CreateFactory()
    oper.SetA(1)
    oper.SetB(2)
    fmt.Println(oper.GetResult())
}

抽象工厂 

抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。

package main
import "fmt"
type GirlFriend struct {
    nationality string
    eyesColor   string
    language    string
}
type AbstractFactory interface {
    CreateMyLove() GirlFriend
}
type IndianGirlFriendFactory struct {
}
type KoreanGirlFriendFactory struct {
}
func (a IndianGirlFriendFactory) CreateMyLove() GirlFriend {
    return GirlFriend{"Indian", "Black", "Hindi"}
}
func (a KoreanGirlFriendFactory) CreateMyLove() GirlFriend {
    return GirlFriend{"Korean", "Brown", "Korean"}
}
func getGirlFriend(typeGf string) GirlFriend {
    var gffact AbstractFactory
    switch typeGf {
    case "Indian":
        gffact = IndianGirlFriendFactory{}
        return gffact.CreateMyLove()
    case "Korean":
        gffact = KoreanGirlFriendFactory{}
        return gffact.CreateMyLove()
    }
    return GirlFriend{}
}
func main() {
    a := getGirlFriend("Indian")
    fmt.Println(a.eyesColor)
}
参考博客: https://blog.csdn.net/wangshubo1989/article/details/79270450            
阅读更多
换一批

没有更多推荐了,返回首页