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

相关推荐
王码码20351 小时前
Go语言的包管理:从GOPATH到Go Modules
后端·golang·go·接口
老王以为5 小时前
深入理解 AbortController:从底层原理到跨语言设计哲学
javascript·设计模式·node.js
白毛大侠6 小时前
Docker vs 虚拟机 vs Go 用户态/内核态:这三组概念
运维·docker·golang·kvm
咬_咬6 小时前
go语言学习(map)
开发语言·学习·golang·map
likerhood7 小时前
抽象工厂设计模式(Abstract Factory Pattern)
设计模式
张涛酱1074567 小时前
AskUserQuestionTool 深入解析:构建人机协作的交互桥梁
spring·设计模式·ai编程
Duang7 小时前
AI 真能自己写出整个 Windows 系统吗?我做了一场无监督实验
算法·设计模式·架构
U盘失踪了7 小时前
go 常量
开发语言·后端·golang
techdashen7 小时前
Go 的新垃圾回收器 Green Tea:一个降低GC CPU开销的大工程
开发语言·后端·golang
止语Lab8 小时前
Go 错误分层实战:从裸奔到三层防线
开发语言·golang