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

相关推荐
xcLeigh4 小时前
Go入门:无类型常量与类型常量的区别
服务器·开发语言·golang
泡沫冰@4 小时前
GO 语言基础
开发语言·算法·golang
骇客野人9 小时前
电商商城微服务架构设计方案(SpringCloud/Go+Vue3+MySQL+ES+RocketMQ)
spring cloud·微服务·golang
码农大叔的博客10 小时前
golang示例:for九九乘法表
开发语言·算法·golang
圣殿骑士-Khtangc10 小时前
Go-sync-Pool对象池最佳实践与源码分析
golang
烬羽11 小时前
NestJS 依赖注入:Controller 里那个没有 new 的 service,到底从哪来的?
设计模式·typescript·nestjs
互联网中的一颗神经元11 小时前
01. Go 内存管理全景架构
java·jvm·golang
有脚就行11 小时前
第24篇-Go-gRPC推理服务-高性能跨语言通信
开发语言·人工智能·后端·golang
用户938515635071 天前
工厂模式与 Nest.js 核心思想 —— 从蜜雪冰城到企业级架构
后端·设计模式·nestjs
圣殿骑士-Khtangc1 天前
Go-Mutex源码解析从自旋到饥饿模式的完整演进
golang