[设计模式 Go实现] 创建型~工厂方法模式

工厂方法模式使用子类的方式延迟生成对象到子类中实现。

Go中不存在继承 所以使用匿名组合来实现

代码实现

package factorymethod

//Operator 是被封装的实际类接口
type Operator interface {
   
	SetA(int)
	SetB(int)
	Result() int
}

//OperatorFactory 是工厂接口
type OperatorFactory interface {
   
	Create() Operator
}

//OperatorBase 是Operator 接口实现的基类,封装公用方法
type OperatorBase struct {
   
	a, b int
}

//SetA 设置 A
func (o *OperatorBase) SetA(a int) {
   
	o.a = a
}

//SetB 设置 B
func (o *OperatorBase) SetB(b int) {
   
	o.b = b
}

//PlusOperatorFactory 是 PlusOperator 的工厂类
type PlusOperatorFactory struct{
   }

func (PlusOperatorFactory) Create() Operator {
   
	return &PlusOperator{
   
		OperatorBase: &OperatorBase{
   },
	}
}

//PlusOperator Operator 的实际加法实现
type PlusOperator struct {
   
	*OperatorBase
}

//Result 获取结果
func (o PlusOperator) Result() int {
   
	return o.a + o.b
}

//MinusOperatorFactory 是 MinusOperator 的工厂类
type MinusOperatorFactory struct{
   }

func (MinusOperatorFactory) Create() Operator {
   
	return &MinusOperator{
   
		OperatorBase: &OperatorBase{
   },
	}
}

//MinusOperator Operator 的实际减法实现
type MinusOperator struct {
   
	*OperatorBase
}

//Result 获取结果
func (o MinusOperator) Result() int {
   
	return o.a - o.b
}

单元测试

package factorymethod

import "testing"

func compute(factory OperatorFactory, a, b int) int {
   
	op := factory.Create()
	op.SetA(a)
	op.SetB(b)
	return op.Result()
}

func TestOperator(t *testing.T) {
   
	var (
		factory OperatorFactory
	)

	factory = PlusOperatorFactory{
   }
	if compute(factory, 1, 2) != 3 {
   
		t.Fatal("error with factory method pattern")
	}

	factory = MinusOperatorFactory{
   }
	if compute(factory, 4, 2) != 2 {
   
		t.Fatal("error with factory method pattern")
	}
}

测试结果

在这里插入图片描述

相关推荐

  1. GO设计模式——2、工厂方法模式创建

    2024-01-04 11:42:01       37 阅读
  2. 设计模式-创建模式-工厂方法模式

    2024-01-04 11:42:01       29 阅读
  3. GO设计模式——1、简单工厂模式创建

    2024-01-04 11:42:01       39 阅读
  4. GO设计模式——3、抽象工厂模式创建

    2024-01-04 11:42:01       38 阅读
  5. [设计模式 Go实现] 创建~单例模式

    2024-01-04 11:42:01       36 阅读
  6. [设计模式 Go实现] 创建~建造者模式

    2024-01-04 11:42:01       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-04 11:42:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-04 11:42:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-04 11:42:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-04 11:42:01       20 阅读

热门阅读

  1. vivado 指定相对位置

    2024-01-04 11:42:01       42 阅读
  2. [NOIP2003 普及组] 乒乓球#洛谷

    2024-01-04 11:42:01       36 阅读
  3. Mybatis-plus分页插件PageHelper的两种不同使用方式

    2024-01-04 11:42:01       37 阅读
  4. Django定制模型管理器

    2024-01-04 11:42:01       47 阅读