golang 设计模式之抽象工厂模式

设计模式 刘宇帅 5年前 阅读量: 2215

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

介绍

  • 意图:提供一个创建一系列相关或则相互依赖对象的接口,而无需指定他们依赖的类。
  • 解决问题:主要解决接口选择的问题
  • 优点:调用方面向接口编程,不用关心具体实现
  • 缺点:扩展新的产品复杂,新增一个新产品需要修改工厂接口和所有工厂类
  • 可应用场景
    • 系统主题:比如一个游戏主题分为男生主题、女生主题

实现

以系统主题为例

结构

代码

游戏颜色

// 颜色接口
type Color interface {
    Color() string
}

// 粉红色主题颜色
type PinkColor struct {
}

func (p *PinkColor) Color() string {
    return "pink"
}

// 蓝色主题颜色
type BlueColor struct {
}

func (b *BlueColor) Color() string {
    return "blue"
}

游戏声音

// 声音接口
type Voice interface {
    Voice() string
}

// 女孩声音
type GirlVoice struct {
}

func (g *GirlVoice) Voice() string {
    return "girl"
}

// 男孩声音
type BoyVoice struct {
}

func (b *BoyVoice) Voice() string {
    return "boy"
}

不同主题

// 主题接口
type ThemeFactory interface {
    GetVoice() Voice
    GetColor() Color
}

// 女生主题
type GirlTheme struct {
}

func (g *GirlTheme) GetVoice() Voice {
    return new(GirlVoice)
}

func (g *GirlTheme) GetColor() Color {
    return new(PinkColor)
}

// 男生主题
type BoyTheme struct {
}

func (b *BoyTheme) GetVoice() Voice {
    return new(BoyVoice)
}

func (b *BoyTheme) GetColor() Color {
    return new(BlueColor)
}

测试用例


import "testing"

func TestAbstractFactory(t *testing.T) {
    // 实例化女生主题
    girlTheme := new(GirlTheme)
    if girlTheme.GetColor().Color() != "pink" || girlTheme.GetVoice().Voice() != "girl" {
        t.Error("GirlTheme error")
    }
    // 实例化男生主题
    boyTheme := new(BoyTheme)
    if boyTheme.GetColor().Color() != "blue" || boyTheme.GetVoice().Voice() != "boy" {
        t.Error("BoyTheme error")
    }
}

测试输出

> $ go test
PASS
ok      github.com/yushuailiu/go-algorithm/pattern/abstractFactory  0.006s

源码地址

提示

功能待开通!


暂无评论~