Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > GoLang工厂模式

深入了解GoLang中的工厂设计模式

作者:未来谁可知

这篇文章主要介绍了深入了解GoLang中的工厂设计模式,工厂模式是一种常用的设计模式,它属于创建型模式,它的主要目的是封装对象的创建过程,将对象的创建过程与对象的使用过程分离,从而提高代码的可维护性和可扩展性,需要详细了解可以参考下文

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包含了IRuleConfigParserISystemConfigParser两个解析器,再分别由jsonRuleConfigParserjsonConfigParserFactory实现对应的解析方法

到此这篇关于深入了解GoLang中的工厂设计模式的文章就介绍到这了,更多相关GoLang工厂模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文