《大话设计模式-Golang》简单工厂模式

需求

实现一个计算器

UML图

在这里插入图片描述

代码

运算接口

type Operation interface {
	GetResult() float64
}

加减乘除实现类

后续有扩展的计算方法,只需要实现Operation接口的GetResult()方法即可

type Number struct {
	numberA float64
	numberB float64
}

//加
type OperationAdd struct {
	Number
}

func (o *OperationAdd) GetResult() float64 {
	return o.numberA + o.numberB
}

//减
type OperationSub struct {
	Number
}

func (o *OperationSub) GetResult() float64 {
	return o.numberA - o.numberB
}

//乘
type OperationMul struct {
	Number
}

func (o *OperationMul) GetResult() float64 {
	return o.numberA * o.numberB
}

//除
type OperationDiv struct {
	Number
}

func (o *OperationDiv) GetResult() float64 {
	if o.numberB == 0 {
		panic("除数不能为0")
	}
	return o.numberA / o.numberB

简单工厂类

package simpleFactory

type OperationFactory struct {
}

func (f *OperationFactory) CreateOperation(numberA, numberB float64, operate string) Operation {
	var operation Operation
	switch operate {
	case "+":
		operation = &OperationAdd{Number{numberA: numberA, numberB: numberB}}
		break
	case "-":
		operation = &OperationSub{Number{numberA: numberA, numberB: numberB}}
		break
	case "*":
		operation = &OperationMul{Number{numberA: numberA, numberB: numberB}}
		break
	case "/":
		operation = &OperationDiv{Number{numberA: numberA, numberB: numberB}}
		break
	default:
		panic("do not support")
	}
	return operation
}

测试

func main() {
	//简单工厂模式
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println(err)
		}
	}()
	var oper simpleFactory.Operation
	factory := new(simpleFactory.OperationFactory)
	oper = factory.CreateOperation(2, 2, "*")
	fmt.Println(oper.GetResult())
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值