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语言学习、求职的社区。

相关推荐
dgvri6 小时前
Windows上安装Go并配置环境变量(图文步骤)
开发语言·windows·golang
逆境不可逃12 小时前
【从零入门23种设计模式18】行为型之备忘录模式
服务器·数据库·设计模式·oracle·职场和发展·迭代器模式·备忘录模式
Real-Staok13 小时前
(集合)C / C++ 设计模式综合
单例模式·设计模式·代理模式
AMoon丶13 小时前
Golang--协程调度
linux·开发语言·后端·golang·go·协程·goroutine
暴躁小师兄数据学院13 小时前
【WEB3.0零基础转行笔记】Go编程篇-第11讲:Gin框架
笔记·golang·web3·区块链·智能合约
AMoon丶13 小时前
Golang--锁
linux·开发语言·数据结构·后端·算法·golang·mutex
sg_knight14 小时前
设计模式实战:代理模式(Proxy)
python·设计模式·代理模式·proxy
Anurmy15 小时前
设计模式之命令模式
设计模式·命令模式
五点六六六1 天前
基于 AST 与 Proxy沙箱 的局部代码热验证
前端·设计模式·架构
王的宝库1 天前
Go 语言:结构体:定义、初始化、方法、组合、Tag、对齐
开发语言·后端·学习·golang