[设计模式 Go实现] 创建型~简单工厂模式

go 语言没有构造函数一说,所以一般会定义NewXXX函数来初始化相关类。 NewXXX 函数返回接口时就是简单工厂模式,也就是说Golang的一般推荐做法就是简单工厂。

代码实现

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)
}

单元测试

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")
	}
}

测试结果

相关推荐
呆萌很2 小时前
【GO】数组练习题
golang
呆萌很4 小时前
【GO】Map练习题
golang
sevenlin4 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
逆境不可逃5 小时前
【从零入门23种设计模式23】行为型之模板模式
java·开发语言·算法·设计模式·职场和发展·模板模式
Aaron_dw8 小时前
QT软件开发设计模式-模板方法模式
qt·设计模式·模板方法模式
Aaron_dw8 小时前
QT软件开发设计模式-观察者模式
qt·观察者模式·设计模式
Geoking.8 小时前
【新手向】go语言最新下载及安装配置教程
开发语言·后端·golang
Chasing__Dreams8 小时前
python--设计模式--13.1--结构性--享元模式
python·设计模式·享元模式
ん贤8 小时前
Go map 底层原理
算法·golang·map
彭于晏Yan9 小时前
Spring Boot中适配器模式的实现方式
spring boot·设计模式·适配器模式