Golang设计模式(工厂模式)

factory.go

// factory
package factory
import (
 "errors"
 "fmt"
)
const (
 Cash = 1
 DebitCard = 2
)
type PaymentMethod interface {
 Pay(amount float32) string
}
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 not recognized!", m))
 }
}
type CashPM struct{}
type DebitCardPM struct{}
func (c *CashPM) Pay(amount float32) string {
 return fmt.Sprintf("%0.2f paid using cash", amount)
}
func (c *DebitCardPM) Pay(amount float32) string {
 return fmt.Sprintf("%#0.2f paid using debit card", amount)
}

factory_test.go

// factorymethod
package factory
import (
 "strings"
 "testing"
)
func TestGetPaymentMethodCash(t *testing.T) {
 payment, err := GetPaymentMethod(Cash)
 if err != nil {
 t.Fatal("A payment method of type 'Cash' must exist")
 }
 msg := payment.Pay(10.30)
 if !strings.Contains(msg, "paid using cash") {
 t.Error("The cash payment method message doesn't correct")
 }
 t.Log("Log:", msg)
}
func TestGetPaymentMethodDebitCard(t *testing.T) {
 payment, err := GetPaymentMethod(DebitCard)
 if err != nil {
 t.Fatal("A payment method of type 'DebitCard' must exist")
 }
 msg := payment.Pay(22.30)
 if !strings.Contains(msg, "paid using debit card") {
 t.Error("The debit card payment method message doesn't correct")
 }
 t.Log("Log:", msg)
}

程序输出如下,


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容