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

相关推荐
songgeb2 小时前
《设计模式之美》之适配器模式
设计模式
Yeniden2 小时前
【设计模式】享元模式(Flyweight)大白话讲解!
java·设计模式·享元模式
乙己4072 小时前
设计模式——单例模式(singleton)
java·c++·单例模式·设计模式
这不小天嘛3 小时前
23 种经典设计模式的名称、意图及适用场景概述
设计模式
Tony Bai4 小时前
从 Python 到 Go:我们失去了什么,又得到了什么?
开发语言·后端·python·golang
雪域迷影11 小时前
Go语言中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·后端·http·golang·get
数据知道14 小时前
Go语言设计模式:适配器模式详解
设计模式·golang·建造者模式
执笔论英雄14 小时前
【设计模式】策略类和依赖注入
设计模式
手把手入门18 小时前
23种设计模式
设计模式
qqxhb18 小时前
系统架构设计师备考第59天——SOA原则&设计模式
设计模式·系统架构·版本管理·标准化·松耦合·可复用·服务粒度