设计模式笔记 - 抽象工厂模式

90 阅读1分钟

抽象工厂模式是一种创建型设计模式,它能创建一系列相关的对象,而无需指定其具体类。


下面看一个例子:

package main

import (
	"fmt"
)

type dialog interface {
	render()
	onClick()
}

type attribute interface {
	setColor(color string)
	setText(text string)
}

type dialogFactory interface {
	newDialog() dialog
	newAttribute() attribute
}

type windowDialog struct{}

func (w *windowDialog) render() {
	fmt.Println("render windowDialog")
}

func (w *windowDialog) onClick() {
	fmt.Println("on click windowDialog")
}

type windowAttribute struct{}

func (w *windowAttribute) setColor(color string) {
    fmt.Println("set color: ", color)
}

func (w *windowAttribute) setText(text string) {
    fmt.Println("set text: ", text)
}

type windowDialogFactory struct{}

func newWindowDialogFactory() dialogFactory {
	return &windowDialogFactory{}
}

func (f *windowDialogFactory) newDialog() dialog {
	return &windowDialog{}
}

func (f * windowDialogFactory) newAttribute() attribute {
	return &windowAttribute{}
}

func newDialogFactory(factoryName string) dialogFactory {
	switch factoryName {
	case "windowDialog":
		return newWindowDialogFactory()
	default:
		return nil
	}
}

func main() {
	f := newDialogFactory("windowDialog")
    
	w := f.newDialog()
	w.render()
	w.onClick()

    a := f.newAttribute()
    a.setColor("red");
    a.setText("hello world")
}

在上面的例子中,通过windowDialogFactory能够分别创建出windowDialogwindowAttribute子类。这也正是抽象工厂方法所要做的事情,将相互独立又有联系的不同类型通过一个工厂创建出来。