问题
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