go 常见设计模式
简单工厂模式
package factory
import "fmt"
type Speaker interface {
Speak()
}
type Dog struct{}
func (d Dog) Speak() {
fmt.Println("小狗汪汪叫")
}
type Cat struct{}
func (c Cat) Speak() {}
func New(id int) Speaker {
if id == 1 {
return &Cat{}
}
return &Dog{}
}
装饰器模式
func main() {
fmt.Println("*******a******")
a := Add(8, 12)
fmt.Println(a)
fmt.Println("****************")
f := LogAdd(Add)
b := f(8, 12)
fmt.Println(b)
}
type AddFun func(int, int) int
// 传入是 AddFun模式,传出也是 AddFun 模式
func LogAdd(f1 AddFun) AddFun {
// 传出是个 AddFun,那么就直接返回该函数模板
afterFun := func(a int, b int) int {
fn := func(a int, b int) int {
star := time.Now()
defer func() {
fmt.Println(time.Since(star))
}()
return f1(a, b) //最后让他return f1就可以了,上面的随便写
}
return fn(a, b)
}
return afterFun
}
func Add(a, b int) int {
time.Sleep(time.Second * 2)
return a + b
}
代理模式
package main
type Subject interface {
Do() string //实际业务,检查是否欠费,检查密码是否正确。
}
type RealSubject struct {
}
func (sb RealSubject) Do() string {
return "以太网智能合约"
}
type Proxy struct {
real RealSubject
money int
}
func (p Proxy) Do() string {
if p.money > 0 {
return p.real.Do()
} else {
return "请充值"
}
}
观察者模式(发布订阅者模式)
// 你在京东上买东西,然后没货了
// 你告诉商店的老板,有货了以后通知你
// 订阅者(抽象的观察者)
type Subject interface {
Attach(observer ...Observer) //表示可以传多个值
Detach(observer Observer)
NoticeObserves(msg interface{})
}
type Observer interface {
Update(msg interface{})
}
// 结构体
type Shop struct {
observeLists []Observer //观察者的列表
}
// Shop 实现一下这个接口
func (shop *Shop) Attach(observer Observer) {
shop.observeLists = append(shop.observeLists, observer)
}
func (shop *Shop) Detach(observer Observer) {
for i := 0; i < len(shop.observeLists); i++ {
if shop.observeLists[i] == observer {
shop.observeLists = append(shop.observeLists[:i], shop.observeLists[i+1:]...)
}
}
}
// 到货了就发通知
func (shop *Shop) NoticeObserves(msg interface{}) {
for _, item := range shop.observeLists {
item.Update(msg)
}
}
// 发送消息
func (shop *Shop) Publish() {
shop.NoticeObserves("货到了!!!")
}
// 建立一个实体
type Observer1 struct {
}
type Observer2 struct {
}
func (o *Observer1) Update(msg interface{}) {
fmt.Println("observ1 收到消息了", msg)
}
func (o *Observer2) Update(msg interface{}) {
fmt.Println("observ2 收到消息了", msg)
}
// 主函数调用
func main() {
shop := new(Shop)
ob1 := new(Observer1)
ob2 := new(Observer2)
shop.Attach(ob1)
shop.Attach(ob2)
shop.Publish()
fmt.Println("******删除一个再试试*******")
// 删除一个再试试
shop.Detach(ob1)
shop.Publish()
}
参考文献
https://www.bilibili.com/video/BV1GD4y1D7D3?p=22&share_source=copy_web
https://www.bilibili.com/video/BV1ma411w7Pc?p=3&share_source=copy_web