Golang設(shè)計(jì)模式(工廠模式)

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 環(huán)境搭建 Golang在Mac OS上的環(huán)境配置 使用Visual Studio Code輔助Go源碼編寫(xiě) VS ...
    隕石墜滅閱讀 5,860評(píng)論 0 5
  • 簡(jiǎn)單工廠模式雖然簡(jiǎn)單,但存在一個(gè)很?chē)?yán)重的問(wèn)題。當(dāng)系統(tǒng)中需要引入新產(chǎn)品時(shí),由于靜態(tài)工廠方法通過(guò)所傳入?yún)?shù)的不同來(lái)創(chuàng)建...
    justCode_閱讀 1,308評(píng)論 1 9
  • 動(dòng)態(tài)調(diào)用動(dòng)態(tài)庫(kù)方法c/c++linuxwindows 關(guān)于動(dòng)態(tài)調(diào)用動(dòng)態(tài)庫(kù)方法說(shuō)明 一、 動(dòng)態(tài)庫(kù)概述 1、 動(dòng)態(tài)庫(kù)的...
    KINGZ1993閱讀 14,203評(píng)論 0 10
  • JAVA面試題 1、作用域public,private,protected,以及不寫(xiě)時(shí)的區(qū)別答:區(qū)別如下:作用域 ...
    JA尐白閱讀 1,270評(píng)論 1 0
  • 西游記里孫悟空捉豬八戒那一段 卻又揪著耳朵,拉著他,叫∶“快走!快走!”那怪道:“輕著些兒!你的手重,揪得我耳根子...
    真是個(gè)聰明的洋娃娃閱讀 185評(píng)論 0 0

友情鏈接更多精彩內(nèi)容