Factory method pattern is a creational pattern that uses factory methods to deal with the problem of cerating objects without having to specify the exact class of the object that will be created.
For example, I define an interface Pokemon and I have multiple types of pokemon that can satisfy this interface.
packagepokemon// Pokemon has a list of moves and attack.typePokemoninterface {Moves() []stringAttack() errorLevel() uint}typecharmanderstruct {// List of attributes}func (c *charmander) Moves() []string {return []string{}}func (c *charmander) Attack() error {returnnil}func (c *charmander) Level() uint {return c.level}typesquirtlestruct {// List of attributes}func (s *squirtle) Moves() []string {return []string{}}func (s *squirtle) Attack() error {returnnil}func (s *squirtle) Level() uint {return s.level}
I am going to use a factory method to create Pokemon.
// Pokemonsconst ( Charmander ="CHARMANDER" Squirtle ="SQUIRTLE")// NewPokemon is a factory method.funcNewPokemon(p string) Pokemon {switch p {case Charmander:return&charmander{}case Squirtle:return&squirtle{}default:returnnil }}