跳到主要内容

Go 设计模式

· 阅读需 1 分钟
ahKevinXy

设计模式的原则

  1. 单一职责原则
  2. 开闭原则
  3. 里氏代换原则
  4. 依赖倒转原则
  5. 接口隔离原则
  6. 合成复用原则
  7. 迪米特法则

创造性模型

简单工厂模式

package main

type Fruit interface {
Show()
}

type AppleFactory struct {
Fruit
}
type BalanceFactory struct {
Fruit
}
type Factory struct {

}

func (f *Factory)CreateFactory(kind string) Fruit {
switch kind {
case "apple":
return new(AppleFactory)
case "balance":
return new(BalanceFactory)

}

return nil
}

func main() {
f := new(Factory)
apple := f.CreateFactory("apple")
apple.Show()
}

抽象工厂