[golang]设计模式--1

本文介绍了在Go语言中如何实现简单工厂模式(使用NewXXX函数创建接口实例)和工厂方法模式(通过子类延迟生成对象,利用匿名组合模拟继承)。通过具体例子展示了如何创建猫和狗的实例以及加法和减法运算的工厂模式应用。
摘要由CSDN通过智能技术生成

前言

设计模式时一套被反复使用,多数人知晓的,经过分类编目的,代码设计经验总结的。使用设计模式是为了可重用代码、让他人更容易理解、保证代码的可靠性。

创建型模式

简单工厂模式

在go中没有构造函数这一说,所以一般会定义NewXXX函数来初始化相关的类型。NewXXX函数返回接口时就是简单工厂模式。

simlpefactory.go

package DesignPatterns

import "fmt"

//简单工厂模式

type Animal interface {
	Eat()
	Call()
}

func NewAnimal(animal string) Animal {
	if animal == "cat" {
		return Cat{}
	} else if animal == "dog" {
		return Dog{}
	}
	return nil
}

//猫

type Cat struct {
}

func (c Cat) Eat() {
	fmt.Println("猫在吃")
}
func (c Cat) Call() {
	fmt.Println("猫再叫")
}

//狗

type Dog struct {
}

func (d Dog) Eat() {
	fmt.Println("狗在吃")
}
func (d Dog) Call() {
	fmt.Println("狗在叫")
}

simplefactory_test.go

package DesignPatterns

import "testing"

func TestCat(t *testing.T) {
	cat := NewAnimal("cat")
	cat.Eat()
	cat.Call()
}

func TestDog(t *testing.T) {
	dog := NewAnimal("dog")
	dog.Eat()
	dog.Call()
}

测试结果
在这里插入图片描述

工厂方法模式

工厂方法模式使用子类的方式延迟生成对象到子类中实现,go中不存在继承,所以使用匿名组合来实现。每一个具体的类都会有自己的工厂类,每一个具体的类实现实际接口,工厂实现初始化实际类。
在这里OperatorBase是封装一个公用类。
factory.go

package DesignPatterns

//工厂模式

// 实际接口

type Operator interface {
	SetA(int)
	SetB(int)
	Result() int
}

//工厂接口

type OperatorFactory interface {
	Create() Operator
}

// Operator基类

type OperatorBase struct {
	a int
	b int
}

func (o *OperatorBase) SetA(a int) {
	o.a = a
}
func (o *OperatorBase) SetB(b int) {
	o.b = b
}

// 加法工厂类

type PlusOperatorFactory struct {
}

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

//加法实现

type PlusOperator struct {
	*OperatorBase
}

func (o PlusOperator) Result() int {
	return o.a + o.b
}

//减法工厂

type MinusOperatorFactory struct{}

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

//减法实现

type MinusOperator struct {
	*OperatorBase
}

func (m MinusOperator) Result() int {
	return m.a - m.b
}

factory_test.go

package DesignPatterns

import (
	"fmt"
	"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")
	}

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

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值