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

相关推荐
端庄的战斗机21 小时前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
开发小程序的之朴21 小时前
认识安企CMS-安装安企CMS的环境要求
nginx·golang·系统架构
北冥you鱼1 天前
abigen 最佳实践:从入门到精通,高效生成 Go 语言合约绑定
开发语言·golang·区块链
北冥you鱼1 天前
Go 语言读取链上数据:从基础到实战
开发语言·后端·golang
饼干哥哥1 天前
我开发了一个「吃掉」别人Skill来升级的饕餮.Skill,现在免费开源
人工智能·设计模式·开源
CaffeinePro1 天前
什么是系统架构?架构师到底在做什么?
设计模式·架构
AI人工智能+电脑小能手1 天前
【大白话说Java面试题 第156题】【06_Spring篇】第16题:Spring 用到了哪些设计模式?
java·spring·设计模式·代理模式·工厂模式
前端百草阁1 天前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式
geovindu1 天前
java: Singleton Pattern
java·开发语言·后端·单例模式·设计模式·创建型模式
ttwuai1 天前
GoFrame + Vue3 后台管理系统实战:CRUD、权限和菜单如何少写重复代码
golang