GO学习系列:设计模式 --- 简单工厂模式

本文介绍如何在Go语言中实现简单工厂模式。通过示例代码详细解释了如何定义抽象产品接口、具体产品类以及工厂类,展示了如何利用工厂类创建所需的具体产品实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计模式一般在面向对象语言(C++)时比较明显。

由于golong中的interface的使用,可以在go中使用设计模式思想。

在此处总结一下设计模式,并学习go的使用。

简单工厂模式:

 -----------                     -----------                        -----------------

| 客户端 |    ----------   | 工厂类 |     ----------     | 抽象产品类 |

 -----------                     -----------                        -----------------

                                                                           /                \

                                                                         /                    \

                                                                       /                        \

                                                                  ----------------          ----------------

                                                                 | 具体产品1 |         | 具体产品2 |

                                                                  ---------------            ---------------

GO的简单工厂实现:

// 运算方法+-*/的实现

// 抽象类

type Operation interface {

    getResult() float64

    setNumA(a float64)

    setNumB(b float64)

}

// 运算操作的数据

type BaseOperation struct {

    numA float64

    numB float64

}

// GO中实现接口的多态的方法(不同的结构实现func)

func (operation *BaseOperation) setNumA(a float64) {

    operation.numA = a

}

func (operation *BaseOperation) setNumB(b float64) {

    operation.numB = b

}

// 具体类:加法

type OperationAdd struct {

    BaseOperation // 匿名

}

func (this *OperationAdd) getResult() float64 { // 加法类的方法实现

    return this.numA + this.numB

}

// 具体类:减法

type OperationSub struct {

    BaseOperation // 匿名

}

func (this *OperationAdd) getResult() float64 {  //减法类的方法实现

    return this.numA - this.numB

}

// 工厂类:主要逻辑实现

type OperationFactory struct {

}

func (this *OperationFactory) createOperation(operation string) (operation Operation) {

    // 根据操作符创建具体的操作类

    switch(operation) {

    case "+" :

        operation = new(OperationAdd)

    case "-" :

        operation = new(OperationSub)

    default:

        panic("wrong operation")

    }   

    return 

// 客户端调用

func main() {

    defer func() {

        if err := recover(); err != nil {

            fmt.Println(err)

        }

    } ()

    var fac OperationFactory //工厂类

    oper := fac.createOperation("+") //利用工厂类创建具体类(抽象类/具体类)

    oper.setNumA(3.0)

    oper.setNumB(2.0)

    oper.getResult() 

}

简单工厂模式的特点:

1)工厂类是整个模式的核心。用户在使用过程中不需要了解每个具体类的实现,

只需要通过工厂类创建所需要的实例,实现了创建者和消费者的分离;

2)模式的逻辑核心为工厂类,当需要增加具体类时,就需要相应的修改工厂类;




                                                                                              

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值