mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-24 13:36:03 +03:00
factory method
This commit is contained in:
parent
131bd3cec7
commit
e04bc0ae49
@ -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)
|
||||||
|
48
creational/factorymethod/main.go
Normal file
48
creational/factorymethod/main.go
Normal 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))
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user