Sergio Leon
Sergio Leon

Reputation: 45

Factory pattern in Go

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.

Upvotes: 0

Views: 2668

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109405

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

Upvotes: 8

Related Questions