关于golang:手撸golang-创建型设计模式-抽象工厂

45次阅读

共计 6785 个字符,预计需要花费 17 分钟才能阅读完成。

手撸 golang 创立型设计模式 形象工厂

缘起

最近温习设计模式
拜读谭勇德的 << 设计模式就该这样学 >>
本系列笔记拟采纳 golang 练习之

形象工厂

形象工厂模式(Abstract Factory Pattern)指提供一个创立一系列相干或相互依赖对象的接口,毋庸指定它们具体的类。意思是客户端不用指定产品的具体类型,创立多个产品族中的产品对象。
_

形象工厂 vs 工厂办法

  • 形象工厂是创立一系列对象, 且这些对象之间可能存在相关性. 工厂办法通常是创立繁多类别的对象

场景

  • 某智能家居场景, 须要通过 app 对立管制各种设施
  • 目前反对智能灯 (ILight) 和空调(IAirConditioner)
  • 不同厂家, 通过提供不同的形象工厂实现, 接入零碎, 提供各种设施的管制

设计

  • 定义 ISmartDevice 接口, 作为所有智能设施的根底接口
  • 定义 ILight, 形象智能灯的接口
  • 定义 IAirConditioner, 形象空调的接口
  • 定义 ISmartFactory, 形象工厂接口, 定义创立智能灯 – CreateLight, 和创立空调 – CreateAirConditioner 的办法
  • 定义并实现 IFactoryRegistry, 提供厂商标识符到形象工厂实例的全局注册表
  • 创立 ”mijia” 子目录, 接入 ”mijia” 厂商的智能灯和空调

    • tMijiaLight, 实现 ILight 接口
    • tMijiaAirConditioner, 实现 IAirConditioner 接口
    • tMijiaFactory, 实现 ISmartFactory 接口, 并在 init 办法中注册到全局的工厂注册表
  • 创立 ”redmi” 子目录, 接入 ”redmi” 厂商的智能灯和空调

abstract_factory_test.go

单元测试

package patterns

import (
    af "learning/gooop/creational_patterns/abstract_factory"
    "testing"

    // 引入并注册厂商 "mijia"
    _ "learning/gooop/creational_patterns/abstract_factory/mijia"

    // 引入并注册厂商 "redmi"
    _ "learning/gooop/creational_patterns/abstract_factory/redmi"
)

func Test_AbstractFactory(t *testing.T) {config := make([]*af.DeviceInfo, 0)
    config = append(config, af.NewDeviceInfo(1, "客厅灯", af.DeviceTypeLight, "mijia", "ML-100"))
    config = append(config, af.NewDeviceInfo(2, "餐厅灯", af.DeviceTypeLight, "redmi", "RL-45"))
    config = append(config, af.NewDeviceInfo(11, "主卧空调", af.DeviceTypeAirConditioner, "mijia", "MA-15"))
    config = append(config, af.NewDeviceInfo(12, "次卧空调", af.DeviceTypeAirConditioner, "redmi", "RA-10"))

    for _,info := range config {factory := af.DefaultFactoryRegistry.Get(info.Vendor())
        if factory == nil {t.Errorf("unsupported vendor: %s", info.Vendor())

        } else {switch info.GetType() {
            case af.DeviceTypeLight:
                e,light := factory.CreateLight(info)
                if e != nil {t.Error(e.Error())
                } else {_ = light.Open()
                    _,_ = light.GetLightMode()
                    _ = light.SetLightMode(1)
                    _,_ = light.GetLightMode()
                    _ = light.Close()}
                break

            case af.DeviceTypeAirConditioner:
                e,ac := factory.CreateAirConditioner(info)
                if e != nil {t.Error(e.Error())
                } else {_ = ac.Open()
                    _,_ = ac.GetTemperature()
                    _ = ac.SetTemperature(26.5)
                    _,_ = ac.GetTemperature()
                    _ = ac.Close()}
                break
            }
        }
    }
}

测试输入

$ go test -v abstract_factory_test.go 
=== RUN   Test_AbstractFactory
tMijiaLight.Open, &{1 客厅灯 Light mijia ML-100}
tMijiaLight.GetLightMode, 0
tMijiaLight.SetLightMode, 1
tMijiaLight.GetLightMode, 1
tMijiaLight.Close, &{1 客厅灯 Light mijia ML-100}
tRedmiLight.Open, &{2 餐厅灯 Light redmi RL-45}
tRedmiLight.GetLightMode, 0
tRedmiLight.SetLightMode, 1
tRedmiLight.GetLightMode, 1
tRedmiLight.Close, &{2 餐厅灯 Light redmi RL-45}
tMijiaLight.Open, &{11 主卧空调 AirConditioner mijia MA-15}
tMijiaAirConditioner.GetTemperature, 0
tMijiaAirConditioner.SetTemperature, 26.5
tMijiaAirConditioner.GetTemperature, 26.5
tMijiaLight.Close, &{11 主卧空调 AirConditioner mijia MA-15}
tRedmiAirConditioner.Open, &{12 次卧空调 AirConditioner redmi RA-10}
tRedmiAirConditioner.GetTemperature, 0
tRedmiAirConditioner.SetTemperature, 26.5
tRedmiAirConditioner.GetTemperature, 26.5
tRedmiAirConditioner.Close, &{12 次卧空调 AirConditioner redmi RA-10}
--- PASS: Test_AbstractFactory (0.00s)
PASS
ok      command-line-arguments  0.002s

ISmartDevice.go

形象智能设施的根底接口

package abstract_factory

type ISmartDevice interface {ID() int
    Name() string

    Open() error
    Close() error}

ILight.go

形象智能灯的接口, 继承 ISmartDevice 接口, 并增加灯光模式的管制办法

package abstract_factory

type ILight interface {
    ISmartDevice

    GetLightMode() (error, int)
    SetLightMode(mode int) error
}

IAirConditioner.go

形象空调的接口, 继承 ISmartDevice 接口, 并增加温度控制的办法

package abstract_factory

type IAirConditioner interface {
    ISmartDevice

    GetTemperature() (error, float64)
    SetTemperature(t float64) error
}

DeviceInfo.go

智能设施的配置信息

package abstract_factory

type DeviceInfo struct {
    iID int
    sName string
    sType DeviceType
    sVendor string
    sModel string
}

type DeviceType string
const DeviceTypeLight DeviceType = "Light"
const DeviceTypeAirConditioner DeviceType = "AirConditioner"

func NewDeviceInfo(id int, name string, devType DeviceType, vendor string, model string) *DeviceInfo {
    return &DeviceInfo{id, name, devType, vendor, model,}
}

func (me *DeviceInfo) ID() int {return me.iID}

func (me *DeviceInfo) Name() string {return me.sName}

func (me *DeviceInfo) Vendor() string {return me.sVendor}

func (me *DeviceInfo) GetType() DeviceType {return me.sType}

FactoryRegistry.go

从工厂标识符到形象工厂实例的全局注册表

package abstract_factory


var DefaultFactoryRegistry = newFactoryRegistry()


type IFactoryRegistry interface {Set(vendor string, factory ISmartFactory)
    Get(vendor string) ISmartFactory
}

type tSimpleFactoryRegistry struct {mFactoryMap map[string]ISmartFactory
}

func newFactoryRegistry() IFactoryRegistry {
    return &tSimpleFactoryRegistry{mFactoryMap: make(map[string]ISmartFactory, 0),
    }
}

func (me *tSimpleFactoryRegistry) Set(vendor string, factory ISmartFactory) {me.mFactoryMap[vendor] = factory
}

func (me *tSimpleFactoryRegistry) Get(vendor string) ISmartFactory {it,ok := me.mFactoryMap[vendor]
    if ok {return it}
    return nil
}

mijia/MijiaFactory.go

“mijia” 厂商实现的工厂类, 在 init 办法中主动注册到全局注册表

package mijia

import (af "learning/gooop/creational_patterns/abstract_factory")

func init() {af.DefaultFactoryRegistry.Set("mijia", newMijiaFactory())
}

type tMijiaFactory struct {
}

func newMijiaFactory() af.ISmartFactory {return &tMijiaFactory{}
}

func (me *tMijiaFactory) CreateLight(info *af.DeviceInfo) (error, af.ILight) {return nil, newMijiaLight(info)
}

func (me *tMijiaFactory) CreateAirConditioner(info *af.DeviceInfo) (error, af.IAirConditioner) {return nil, newMijiaAirConditioner(info)
}

mijia/MijiaLight.go

“mijia” 厂商的智能灯实现类

package mijia

import (
    "fmt"
    af "learning/gooop/creational_patterns/abstract_factory"
)

type tMijiaLight struct {
    af.DeviceInfo
    iMode int
}


func newMijiaLight(info *af.DeviceInfo) *tMijiaLight {
    return &tMijiaLight{*info, 0,}
}

func (me *tMijiaLight) Open() error {fmt.Printf("tMijiaLight.Open, %v\n", &me.DeviceInfo)
    return nil
}

func (me *tMijiaLight) Close() error {fmt.Printf("tMijiaLight.Close, %v\n", &me.DeviceInfo)
    return nil
}

func (me *tMijiaLight) GetLightMode() (error, int) {fmt.Printf("tMijiaLight.GetLightMode, %v\n", me.iMode)
    return nil, me.iMode
}

func (me *tMijiaLight) SetLightMode(mode int) error {fmt.Printf("tMijiaLight.SetLightMode, %v\n", mode)
    me.iMode = mode
    return nil
}

mijia/MijiaAirConditioner

“mijia” 厂商的空调实现类

package mijia

import (
    "fmt"
    af "learning/gooop/creational_patterns/abstract_factory"
)

type tMijiaAirConditioner struct {
    af.DeviceInfo

    fTemperature float64
}


func newMijiaAirConditioner(info *af.DeviceInfo) *tMijiaAirConditioner {
    return &tMijiaAirConditioner{*info, 0,}
}

func (me *tMijiaAirConditioner) Open() error {fmt.Printf("tMijiaLight.Open, %v\n", &me.DeviceInfo)
    return nil
}

func (me *tMijiaAirConditioner) Close() error {fmt.Printf("tMijiaLight.Close, %v\n", &me.DeviceInfo)
    return nil
}

func (me *tMijiaAirConditioner) GetTemperature() (error, float64) {fmt.Printf("tMijiaAirConditioner.GetTemperature, %v\n", me.fTemperature)
    return nil, me.fTemperature
}

func (me *tMijiaAirConditioner) SetTemperature(t float64) error {
    me.fTemperature = t
    fmt.Printf("tMijiaAirConditioner.SetTemperature, %v\n", me.fTemperature)
    return nil
}

redmi/RedmiFactory.go

“redmi” 厂商实现的工厂类, 在 init 办法中主动注册到全局注册表. 代码略

redmi/RedmiLight.go

“redmi” 厂商的智能灯实现类. 代码略.

redmin/RedmiAirConditioner.go

“redmin” 厂商的空调实现类. 代码略.

形象工厂模式小结

形象工厂模式的长处
(1)当须要产品族时,形象工厂能够保障客户端始终只应用同一个产品的产品族。
(2)形象工厂加强了程序的可扩展性,对于新产品族的减少,只需实现一个新的具体工厂即可,不须要对已有代码进行批改,合乎开闭准则。
形象工厂模式的毛病
(1)规定了所有可能被创立的产品汇合,产品族中扩大新的产品艰难,须要批改形象工厂的接口。
(2)减少了零碎的抽象性和了解难度。
_
(end)

正文完
 0