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

测试结果

相关推荐
Query*44 分钟前
Java 设计模式——建造者模式:从原理到实战的极简指南
java·设计模式·建造者模式
Tiny_React2 小时前
智能体设计模式-CH05:工具使用(Tool Use)
设计模式
舒克起飞了2 小时前
设计模式——建造者模式
设计模式·建造者模式
Tiny_React2 小时前
智能体设计模式-CH06:规划(Planning)
设计模式
Meteors.5 小时前
23种设计模式——迭代器模式 (Iterator Pattern)详解
java·设计模式·迭代器模式
云闲不收5 小时前
golang的一些技巧
开发语言·后端·golang
Tiny_React6 小时前
智能体设计模式-CH03:并行化(Parallelization)
设计模式
Tiny_React6 小时前
智能体设计模式-CH02:路由(Routing)
设计模式
Deschen6 小时前
设计模式-组合模式
java·设计模式·组合模式
Tiny_React8 小时前
智能体设计模式-CH01:提示链(Prompt Chaining)
设计模式