Skip to content

Commit

Permalink
adding factory example 🔥
Browse files Browse the repository at this point in the history
  • Loading branch information
shubhamzanwar committed Sep 24, 2020
1 parent 9e8ab81 commit 73c506a
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 1-factory/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"bufio"
"fmt"
"os"
"strings"

"./pets"
)

func describePet(pet pets.Pet) string {
return fmt.Sprintf("%s is %d years old. It's sound is %s", pet.GetName(), pet.GetAge(), pet.GetSound())
}

func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Are you a dog person or cat person? (dog/cat)")
petType, _ := reader.ReadString('\n')
petType = strings.Split(petType, "\n")[0]

pet := pets.PetFactory(petType)
petDescription := describePet(pet)

fmt.Println(petDescription)
}
19 changes: 19 additions & 0 deletions 1-factory/pets/cat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package pets

type cat struct {
name string
sound string
age int
}

func (c cat) GetName() string {
return c.name
}

func (c cat) GetAge() int {
return c.age
}

func (c cat) GetSound() string {
return c.sound
}
19 changes: 19 additions & 0 deletions 1-factory/pets/dog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package pets

type dog struct {
name string
sound string
age int
}

func (d dog) GetName() string {
return d.name
}

func (d dog) GetAge() int {
return d.age
}

func (d dog) GetSound() string {
return d.sound
}
26 changes: 26 additions & 0 deletions 1-factory/pets/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package pets

// Pet defines the general structure of all pets
type Pet interface {
GetName() string
GetSound() string
GetAge() int
}

// PetFactory is a factory that return the pet requested
func PetFactory(petType string) Pet {
if petType == "dog" {
return dog{
name: "Chester",
age: 2,
sound: "bark",
}
} else if petType == "cat" {
return cat{
name: "Mr. Buttons",
age: 3,
sound: "meow",
}
}
return nil
}

0 comments on commit 73c506a

Please sign in to comment.