Factory pattern in Go

夙愿已清 提交于 2020-05-26 10:08:05

问题


I'm trying to implement a factory pattern with Go, here is the example https://play.golang.org/p/ASU0UiJ0ch

I have a interface Pet and a struct Dog so Dog should have the properties of Pet, on this case only one which is the specie, when trying to initialize the object Dog via the factory NewPet, can someone please advise.


回答1:


Your NewPet factory returns type Pet, not *Pet in the type assertion. (you rarely ever want a pointer to an interface)

return Pets[pet].(func(string) Pet)(name)

Your Pet constructors also need to return type Pet in order to satisfy the factory function signature, which you can simplify as:

func NewDog(name string) Pet {
    return &Dog{
        name: name,
    }
}

Now since all the functions have the same signature, you can define the Pets map with that signature to avoid the need for the type assertion

var Pets = map[string]func(name string) Pet

https://play.golang.org/p/-cz1vX-cMs



来源:https://stackoverflow.com/questions/46549800/factory-pattern-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!