天天看点

go设计模式之美 - 工厂模式

go设计模式之美 - 工厂模式

1. 定义

工厂模式是一种创建型设计模式,有了工厂只需要知道要制造的东西名字,就能让对应工厂进行生产,不用关心生产过程。

2. 优点

1、一个调用者想创建一个对象,只要知道其名称就可以了。

2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。

3、屏蔽产品的具体实现,调用者只关心产品的接口。

3. 代码实现

3.1 普通工厂
package factory

type HeroFactory interface {
	Name(str string)
}
type WoManHero struct {
	Age string
	Hight float32
}

func (w WoManHero) Name(str string) {
	panic("implement me")
}

type ManHero struct {
	Age string
	Hight float32
}

func (m ManHero) Name(str string) {
	panic("implement me")
}
// 简单工厂模式
func NewHeroFactory(sex int) HeroFactory {
	switch sex {
	case 0:
		return ManHero{}
	case 1:
		return WoManHero{}
	default:
		return nil
	}
}
           
3.2 工厂方法
package factory

type IRuleHeroFactor interface {
	CreateHero() HeroFactory
}
type WoManHeroFactory struct {

}

func (s WoManHeroFactory) CreateHero() HeroFactory {
	return &WoManHero{}
}

type ManHeroFactory struct {
	
}

func (p ManHeroFactory) CreateHero() HeroFactory {
	return &ManHero{}
}
// NewIRuleConfigParserFactory 用一个简单工厂封装工厂方法
func NewIRuleConfigParserFactory(t string) IRuleHeroFactor {
	switch t {
	case "M":
		return ManHeroFactory{}
	case "W":
		return WoManHeroFactory{}
	}
	return nil
}
           
3.3 抽象工厂

抽象接口里包含了各自的工厂方法或者普通工厂,再由各自实现自己的工厂

package factory

// IRuleConfigParser IRuleConfigParser
type IRuleConfigParser interface {
	Parse(data []byte)
}

// jsonRuleConfigParser jsonRuleConfigParser
type jsonRuleConfigParser struct{}

// Parse Parse
func (j jsonRuleConfigParser) Parse(data []byte) {
	panic("implement me")
}

// ISystemConfigParser ISystemConfigParser
type ISystemConfigParser interface {
	ParseSystem(data []byte)
}

// jsonSystemConfigParser jsonSystemConfigParser
type jsonSystemConfigParser struct{}

// Parse Parse
func (j jsonSystemConfigParser) ParseSystem(data []byte) {
	panic("implement me")
}


// IConfigParserFactory 工厂方法接口
type IConfigParserFactory interface {
	CreateRuleParser() IRuleConfigParser
	CreateSystemParser() ISystemConfigParser
}

type jsonConfigParserFactory struct{}

func (j jsonConfigParserFactory) CreateRuleParser() IRuleConfigParser {
	return jsonRuleConfigParser{}
}

func (j jsonConfigParserFactory) CreateSystemParser() ISystemConfigParser {
	return jsonSystemConfigParser{}
}
           

IConfigParserFactory

包含了

IRuleConfigParser

ISystemConfigParser

两个解析器,再分别由

jsonRuleConfigParser

jsonConfigParserFactory

实现对应的解析方法