[设计模式 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")
	}
}

测试结果

相关推荐
o0o_-_16 小时前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
努力也学不会java19 小时前
【设计模式】状态模式
java·设计模式·状态模式
.豆鲨包19 小时前
【设计模式】单例模式
java·单例模式·设计模式
lpfasd12320 小时前
第2课:Agent系统架构与设计模式
设计模式·系统架构
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(1)
c++·设计模式·原型模式
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(2)
c++·设计模式·原型模式
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(3)
c++·设计模式·原型模式
new_daimond1 天前
设计模式-装饰器模式详解
设计模式·装饰器模式