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


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

查看所有标签

猜你喜欢:

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

探索需求

探索需求

章柏幸、王媛媛、谢攀、杰拉尔德・温伯格、唐纳德・高斯 / 章柏幸、王媛媛、谢攀 / 清华大学出版社 / 2004-7-1 / 39.00元

本书将与您一起寻找"什么是客户真正想要的"这一问题的答案。 本书着眼于系统设计之前的需求过程,它是整个开发过程(如何设计人们想要的产品和系统)中最有挑战性的那部分。通过对一些需求分析中的常见误区和问题的分析和讨论,从和客户沟通开始,深入研究一些可能的需求,澄清用户和开发者期望值,最终给出了能够大幅度提高项目成功几率的一些建议方法。 本书由该领域内公认的两位作者合著,搜集了他们在大大小小......一起来看看 《探索需求》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具