From e04bc0ae4973cec5dc46c6a94425bbfccf08ba7e Mon Sep 17 00:00:00 2001 From: Jian Han Date: Sat, 11 Nov 2017 11:48:56 +1000 Subject: [PATCH] factory method --- channel/buffed/main.go | 1 + creational/factorymethod/main.go | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 creational/factorymethod/main.go diff --git a/channel/buffed/main.go b/channel/buffed/main.go index 52a1d19..8a96d42 100644 --- a/channel/buffed/main.go +++ b/channel/buffed/main.go @@ -11,6 +11,7 @@ func main() { ch := make(chan int, 2) go func(ch chan int) { + for i := 1; i <= 5; i++ { ch <- i fmt.Println("Func goroutine sends data: ", i) diff --git a/creational/factorymethod/main.go b/creational/factorymethod/main.go new file mode 100644 index 0000000..e9d5613 --- /dev/null +++ b/creational/factorymethod/main.go @@ -0,0 +1,48 @@ +package main + +import ( + "errors" + "fmt" + + "github.com/davecgh/go-spew/spew" +) + +type PaymentMethod interface { + Pay(amount float32) string +} + +const ( + Cash = 1 + DebitCard = 2 +) + +type CashPM struct{} + +func (c *CashPM) Pay(amount float32) string { + return fmt.Sprintf("%v paid using cash\n", amount) +} + +type DebitCardPM struct{} + +func (c *DebitCardPM) Pay(amount float32) string { + return fmt.Sprintf("%v paid using DebitCard\n", amount) +} + +func GetPaymentMethod(m int) (PaymentMethod, error) { + switch m { + case Cash: + return new(CashPM), nil + case DebitCard: + return new(DebitCardPM), nil + default: + return nil, errors.New(fmt.Sprintf("Payment method %d was not recognized")) + } +} + +func main() { + paymentMethod, err := GetPaymentMethod(Cash) + if err != nil { + fmt.Sprintf("Error %s", err.Error()) + } + spew.Dump(paymentMethod.Pay(32)) +}