factory method

This commit is contained in:
Jian Han 2017-11-11 11:48:56 +10:00
parent 131bd3cec7
commit e04bc0ae49
2 changed files with 49 additions and 0 deletions

View File

@ -11,6 +11,7 @@ func main() {
ch := make(chan int, 2) ch := make(chan int, 2)
go func(ch chan int) { go func(ch chan int) {
for i := 1; i <= 5; i++ { for i := 1; i <= 5; i++ {
ch <- i ch <- i
fmt.Println("Func goroutine sends data: ", i) fmt.Println("Func goroutine sends data: ", i)

View File

@ -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))
}