抽象工厂模式(Abstract Factory Pattern)

193 阅读2分钟

简述

抽象工厂模式(Abstract Factory Pattern)是属于创建型模式。在抽象工厂模型中,接口是负责创建相关对象的工厂,不需要显示指定他们的类。每个生成的工厂都能按照工厂模式提供对象。与工厂方法模式的区别是:工厂方法模式新增一个类型的对象,需要在Switch-case中填加新类型对象的创建处理,随着新增的类型越来越多,工程的职责也会越来越重,违反了单一职责原则,抽象工厂模式就是解决该问题

应用

不同条件下创建不同实例,例如:

  • 根据不同环境读取不同配置文件
  • 根据不同的条件访问不同的数据库mysql、MongoDB

实现

  • 定义公共的接口(interface)

    type *** interface {}

  • 定义struct结构体,并实现公共的接口(interface)

  • 定义抽象工厂接口(interface)

    type ***Factory interface {

        ***funcName interfaceName // 创建不同类型实例的方式
    

    }

  • 定义工厂struct结构体并实现工厂的抽象方法,用于不同实例的创建,方法的参数通常是实例的struct类别,实例化通常是利用反射,根据struct类别进行进行实例化

    func (e *FactoryStruct) funcName(eventType reflect.Type) interfaceName {}

示例

抽象工厂定义:

package factory

import "reflect"

// 定义接口
type Event interface {
   EventType() string
   Content() string
}

// 定义 StartEvent 结构体
type StartEvent struct {
   typeName string
   content  string
}

// StartEvent结构体实现Event接口的EventType函数
func (e *StartEvent) EventType() string {
   return e.typeName
}

// StartEvent结构体实现Event接口的Content函数
func (e *StartEvent) Content() string {
   return e.content
}

// 定义 EndEvent 结构体
type EndEvent struct {
   typeName string
   content  string
}

// EndEvent结构体实现Event接口的EventType函数
func (e *EndEvent) EventType() string {
   return e.typeName
}

// EndEvent结构体实现Event接口的Content函数
func (e *EndEvent) Content() string {
   return e.content
}

// 定义抽象的工厂接口
type Factory interface {
   Create(reflect.Type) Event
}

// 定义事件工厂struct
type EventFactory struct {
}

// 利用反射机制,根据不同事件类型创建对象
func (e *EventFactory) Create(eventType reflect.Type) Event {
   return reflect.New(eventType).Interface().(Event)
}

调用抽象工厂模式:

package main

import (
   "github.com/design/pattern/factory"
   "reflect"
)

func main() {
   // 工厂抽象模式
   abstractFactory := factory.EventFactory{}
   event := abstractFactory.Create(reflect.TypeOf(factory.StartEvent{}))
   event.Content()
}