您的位置:首页 > 编程语言 > Go语言

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

2017-07-21 15:37 337 查看
设计模式一般在面向对象语言(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)模式的逻辑核心为工厂类,当需要增加具体类时,就需要相应的修改工厂类;

                                                                                              
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: