Go语言设计模式·简单工厂模式

go 语言没有构造函数一说,所以一般会定义NewXXX函数来初始化相关类。

NewXXX 函数返回接口时就是简单工厂模式,也就是说Golang的一般推荐做法就是简单工厂。

在这个simplefactory包中只有API 接口和NewAPI函数为包外可见,封装了实现细节。

simple.go代码
go 复制代码
package simplefactory

import "fmt"

//API is interface
type API interface {
    Say(name string) string
}

//NewAPI return Api instance by type
func NewAPI(t int) API {
    if t == 1 {
        return &hiAPI{}
    } else if t == 2 {
        return &helloAPI{}
    }
    return nil
}

//hiAPI is one of API implement
type hiAPI struct{}

//Say hi to name
func (*hiAPI) Say(name string) string {
    return fmt.Sprintf("Hi, %s", name)
}

//HelloAPI is another API implement
type helloAPI struct{}

//Say hello to name
func (*helloAPI) Say(name string) string {
    return fmt.Sprintf("Hello, %s", name)
}
simple_test.go代码
go 复制代码
package simplefactory

import "testing"

//TestType1 test get hiapi with factory
func TestType1(t *testing.T) {
    api := NewAPI(1)
    s := api.Say("Tom")
    if s != "Hi, Tom" {
        t.Fatal("Type1 test fail")
    }
}

func TestType2(t *testing.T) {
    api := NewAPI(2)
    s := api.Say("Tom")
    if s != "Hello, Tom" {
        t.Fatal("Type2 test fail")
    }
}

本文节选于Go合集《Go语言设计模式》GOLANG ROADMAP 一个专注Go语言学习、求职的社区。

相关推荐
Overboom4 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式
@大迁世界7 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
赴前尘9 小时前
Go 微服务框架排行榜(按 GitHub Star 排序)
微服务·golang·github
数据智能老司机11 小时前
数据工程设计模式——冷热数据存储
大数据·设计模式·架构
爱学习的小熊猫_12 小时前
设计模式之责任链模式
设计模式·责任链模式
闲不住的李先森12 小时前
乐观更新
前端·react.js·设计模式
数据智能老司机15 小时前
数据工程设计模式——实时摄取与处理
大数据·设计模式·架构
Asort18 小时前
JavaScript设计模式(七)——桥接模式:解耦抽象与实现的优雅之道
前端·javascript·设计模式
原则猫19 小时前
单例模式工程运用
前端·设计模式