go设计模式之简单工厂模式

Posted by     "richie" on Tuesday, July 2, 2019

简单工厂模式

go 语言没有构造函数,所以一般定义NewXXX函数来初始化相关类.NewXXX函数返回接口时就是简单工厂模式, 也就是说Golang的一般推荐做法就是简单工厂.

在这个simplefactory 包中有API 接口和NewAPI函数为包外可见, 话不多说见代码:

# simple.go
package simplefactory

import "fmt"

//API is interface

type API interface {
	Say(name string) string
}

//NewAPI return Api instace 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{}

func (*hiAPI) Say(name string) string {
	return fmt.Sprintf("Hi, %s", name)
}

type helloAPI struct{}

func (*helloAPI) Say(name string) string {
	return fmt.Sprintf("Hello,%s", name)
}

测试代码

package simplefactory

import "testing"

//TestType1 test get hiapi with factory
func TestType1(t *testing.T) {
	api := NewAPI(1)
	s := api.Say("Tom")
	t.Log(s)
	if s != "Hi, Tom" {
		t.Fatal("Type1 test fail")
	}
}

func TestType2(t *testing.T) {
	api := NewAPI(2)
	s := api.Say("Tom")
	t.Log(s)
	if s != "Hello, Tom" {
		t.Fatal("Type2 test fail")
	}
}
 ~/G/s/l/g/golang-design-pattern  go test -v                                                                                                                                                        二  7/ 2 19:48:14 2019
=== RUN   TestType1
--- PASS: TestType1 (0.00s)
    simple_test.go:9: Hi, Tom
=== RUN   TestType2
--- FAIL: TestType2 (0.00s)
    simple_test.go:18: Hello,Tom
    simple_test.go:20: Type2 test fail
FAIL
exit status 1
FAIL    _/Users/finup/GoglandProjects/src/learn-demo/golang-design/golang-design-pattern        0.006s

「真诚赞赏,手留余香」

Richie Time

真诚赞赏,手留余香

使用微信扫描二维码完成支付