Golang设计模式(工厂模式)

栏目: Go · 发布时间: 6年前

内容简介:factory.gofactory_test.go程序输出如下,

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

程序输出如下,

Golang设计模式(工厂模式)

image.png


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SQL基础教程

SQL基础教程

MICK / 孙淼、罗勇 / 人民邮电出版社 / 2013-8-1 / CNY 69.00

本书介绍了关系数据库以及用来操作关系数据库的SQL语言的使用方法,提供了大量的示例程序和详实的操作步骤说明,读者可以亲自动手解决具体问题,循序渐进地掌握SQL的基础知识和技巧,切实提高自身的编程能力。在每章结尾备有习题,用来检验读者对该章内容的理解程度。另外本书还将重要知识点总结为“法则”,方便大家随时查阅。 本书适合完全没有或者具备较少编程和系统开发经验的初学者,也可以作为大中专院校的教材......一起来看看 《SQL基础教程》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具