Created
July 3, 2021 02:10
-
-
Save lemissel/fd9c4cf8be973b52ae9c1285d56e0a44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WARNING: This file is a simple annotation and don`t run | |
type Person struct { | |
Name string | |
Age int | |
} | |
func (p Person) Greet() { | |
fmt.Println("Hi! I'm %s", p.Name) | |
} | |
# Simple factory | |
func NewPerson(name string, age int) Person { | |
return Person{ | |
Name: name, | |
Age: age, | |
} | |
} | |
# Returns a point to Person | |
func NewPerson(name string, age int) *Person { | |
return &Person{ | |
Name: name, | |
Age: age, | |
} | |
} | |
# Interface factories | |
type Person interface { | |
Greet() | |
} | |
type person struct { | |
name string | |
age int | |
} | |
func (p person) Greet() { | |
fmt.Println("Hi! I'm %s", p.name) | |
} | |
# now, NewPerson returns an interface, and not the person struct itself | |
func NewPerson(name string, age int) Person { | |
return person{ | |
name: name, | |
age, age, | |
} | |
} | |
# You can use the same implementation to return a pointer of person | |
func NewPerson(name string, age int) Person { | |
return &person{ | |
name: name, | |
age: age, | |
} | |
} | |
# Factory generators | |
type Animal struct { | |
species string | |
age int | |
} | |
type AnimalHouse struct { | |
name string | |
sizeInMeters int | |
} | |
type AnimalFactory struct { | |
species string | |
houseName string | |
} | |
func (af AnimalFactory) NewAnimal(age int) { | |
return Animal{ | |
species: af.species, | |
age: age, | |
} | |
} | |
func (af AnimalFactory) NewHouse(sizeInMeters int) { | |
return Animal{ | |
name: af.houseName, | |
sizeInMeters: sizeInMeters, | |
} | |
} | |
docFactory := AnimalFactory{ | |
species: "dog", | |
houseName: "kennel", | |
} | |
dog := dogFactory.NewAnimal(2) | |
kennel := dogFactory.NewHouse(3) | |
horseFactory := AnimalFactory{ | |
species: "horse", | |
houseName: "stable", | |
} | |
horseFactory.NewAnimal(12) | |
horseFactory.NewHouse(30) | |
// Factory functions | |
type Person struct { | |
name string | |
age int | |
} | |
func NewPersonFactory(age int) func(name string) Person { | |
return func(name string) Person { | |
return Person{ | |
name: name, | |
age: age, | |
} | |
} | |
} | |
newBaby := NewPersonFactory(1) | |
baby:= newBaby("Leo") | |
newTeenager := NewPersonFactory(15) | |
teen := newTeenager("Kaka") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment