创建型模式
1 创建型模式
Section titled “1 创建型模式”- 简单工厂模式(Simple Factory)
- 单例模式(Singleton)
- 工厂方法模式(Factory Method)
- 抽象工厂模式(Abstract Factory)
- 创建者模式(Builder)
- 原型模式(Prototype)
1.1 简单工厂模式
Section titled “1.1 简单工厂模式”Go中没有构造函数,一般都是以NewXxx函数来进行相关初始化工作,当NewXxx函数返回接口时,这就是一个简单工厂模式,包中会封装接口的实现细节。如:
package simple
type API interface { Do()}
func NewAPI() API { return api{}}
type api struct {}
func (a api) Do() { //TBD...}使用
var api = simple.NewAPI()api.DO()1.2 单例模式
Section titled “1.2 单例模式”单例模式将类型的实例化限制为单个对象。
package singleton
type singleton map[string]string
var ( once sync.Once
instance singleton)
func New() singleton { once.Do(func() { instance = make(singleton) })
return instance}使用
s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])//This is that经验:
单例模式表现的是一个全局状态,同时在大多数时候会降低可测试性。
1.3 工厂方法模式
Section titled “1.3 工厂方法模式”TBD…
1.4 抽象工厂模式
Section titled “1.4 抽象工厂模式”TBD…
1.5 创建者模式
Section titled “1.5 创建者模式”TBD…
1.6 原型模式
Section titled “1.6 原型模式”TBD…