创建型模式,共五种:简单工厂模式、工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
1.简单工厂模式,一般是以NewXXX 返回 interface(接口),然后根据这个 返回的接口对象,调用对象实现接口的方法,就可以了
2.工厂方法模式:使用子类的方式延迟生成对象到子类中实现
package test
import (
"fmt"
"testing"
)
type ParseInterface interface {
parseConfigFile()
}
type parser struct {
name string
}
func (y *parser) parseConfigFile() {
fmt.Println("config name is:", y.name)
}
type jsonParser struct {
parser
}
func newJsonParser() ParseInterface {
return &jsonParser{
parser{
name: "json",
},
}
}
type yamlParser struct {
parser
}
func newYamlParser() ParseInterface {
return &yamlParser{
parser{
name: "yaml",
},
}
}
func sFactory(t int) ParseInterface {
var obj ParseInterface
switch t {
case 1:
obj = newJsonParser()
case 2:
obj = newYamlParser()
default:
fmt.Println("类型错误")
}
return obj
}
func TestFactory(t *testing.T) {
ft := sFactory(1)
ft.parseConfigFile()
//=== RUN TestFactory
//config name is: json
//--- PASS: TestFactory (0.00s)
//PASS
//
//Process finished with the exit code 0
}
3.单例模式
package test
import (
"fmt"
"sync"
"testing"
)
type user struct {
Name string
}
var once sync.Once //通过这个实现单次加载
var userInstance *user
func NewUser() *user {
once.Do(func() {
userInstance = new(user)
})
return userInstance
}
func TestSingle(t *testing.T) {
//user1 := NewUser()
//user1.Name = "测试11111111111"
//fmt.Printf("user1 p is:%p\n", user1)
//
//user2 := NewUser()
//user2.Name = "测试22222222222222"
//fmt.Printf("user2 p is:%p\n", user2)
//打印结果,user1和user2的地址相同
//=== RUN TestSingle
//user1 p is:0xc00070a1f0
//user2 p is:0xc00070a1f0
//--- PASS: TestSingle (0.00s)
//PASS
//
//Process finished with the exit code 0
onceFunc := func() {
fmt.Println("func is coming")
}
for i := 0; i < 5; i++ {
once.Do(onceFunc)
}
// 打印结果 只会输出一次;还加了 debug 调试
//=== RUN TestSingle
//func is coming
//--- PASS: TestSingle (31.72s)
//PASS
//
//Debugger finished with the exit code 0
}
