必须掌握的Golang23种设计模式之简单工厂模式

go 语言没有构造函数一说,所以一般会定义NewXXX函数来初始化相关类。

NewXXX 函数返回接口时就是简单工厂模式,也就是说Golang的一般推荐做法就是简单工厂。

在这个simplefactory包中只有API 接口和NewAPI函数为包外可见,封装了实现细节。

查看全部设计模式:http://www.golang.ren/article/6477

simple.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代码

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")

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容