[go设计模式]工厂方法模式

简单工厂就是生产整个计算器,而工厂方法只生产计算器的一部分;

原有的简单工厂可以生'+' '-' '*' '/' ;但是如果添加新的部件'%',厂房就

需要扩充、修改很可以会影响原来部件的正常生产,这就违背了开放封闭原则;

而工厂方法则不存在这个问题;我新开一个工厂专门生产'%'就可以了。

网易云课堂:http://m.study.163.com/provider/480000001930416/index.htm?share=2&shareId=480000001930416

package main

import (
	"fmt"
)

type Operation interface {
	Exe(int, int) int
}

type FactoryAdd struct{}
type OperationAdd struct{}

func (this *FactoryAdd) Create() Operation {
	return &OperationAdd{}
}

func (this *OperationAdd) Exe(a int, b int) int {
	return a + b
}

type FactorySub struct{}
type OperationSub struct{}

func (this *FactorySub) Create() Operation {
	return &OperationSub{}
}

func (this *OperationSub) Exe(a int, b int) int {
	return a - b
}

type FactoryMul struct{}
type OperationMul struct{}

func (this *FactoryMul) Create() Operation {
	return &OperationMul{}
}

func (this *OperationMul) Exe(a int, b int) int {
	return a * b
}

type FactoryDiv struct{}
type OperationDiv struct{}

func (this *FactoryDiv) Create() Operation {
	return &OperationDiv{}
}

func (this *OperationDiv) Exe(a int, b int) int {
	return a / b
}

// 新增一个"%"操作,不影响原来的代码,符合开放封闭原则
type FactoryMod struct{}
type OperationMod struct{}

func (this *FactoryMod) Create() Operation {
	return &OperationMod{}
}

func (this *OperationMod) Exe(a int, b int) int {
	return a % b
}

func main() {

	fmt.Println(
		(&FactoryAdd{}).Create().Exe(10, 5),
		(&FactorySub{}).Create().Exe(10, 5),
		(&FactoryMul{}).Create().Exe(10, 5),
		(&FactoryDiv{}).Create().Exe(10, 5),
		(&FactoryMod{}).Create().Exe(10, 5))
}

输出结果:

15 5 50 2 0

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值