使用Go实现23种设计模式——结构型模式(下)

外观模式

隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口,使得这一子系统更加容易使用

适用场景

  1. 为一个复杂子系统提供一个简单接口供外界访问

Go语言实现

type Animal struct {
	dog *Dog
	cat *Cat
}

func NewAnimal() *Animal {
	return &Animal{
		dog: &Dog{},
		cat: &Cat{},
	}
}

func (a *Animal) Speak() {
	a.dog.Speak()
	a.cat.Speak()
}

type Dog struct {}

func (a *Dog) Speak() {
	fmt.Println("汪汪汪")
}

type Cat struct {}

func (a *Cat) Speak() {
	fmt.Println("喵喵喵")
}

func main() {
	a := NewAnimal()
	a.Speak()
}

外观模式优点

  1. 降低了子系统与客户端之间的耦合度,子系统的变化不影响调用它的客户端
  2. 对客户屏蔽了子系统组件,减少了客户端处理对象的数目并使得子系统使用更加方便

外观模式缺点

  1. 不能很好的限制客户使用子系统类,容易带来未知风险
  2. 增加新的子系统可能需要修改外观类,违背了"开闭原则"

享元模式

运用共享技术有效的支持大量细粒度的对象

适用场景

  1. 如果程序中使用了大量的对象,且这些对象造成了很大的储存开销
  2. 如果对象的大多数状态可以给外部状态,如果删除对象的外部状态,可以用相对较少的共享对象取代很多对象

Go语言实现

type IFlyWeight interface {
	Run()
}

type FlyWeight struct {
	key string
}

func (f FlyWeight) Run() {
	fmt.Println(f.key)
}

type FactoryFlyWeight struct {
	flyWeight map[string]FlyWeight
}

func NewFactoryFlyWeight() *FactoryFlyWeight {
	return &FactoryFlyWeight{flyWeight: make(map[string]FlyWeight)}
}

func (f *FactoryFlyWeight) GetFlyWeight(key string) (fly FlyWeight) {
	var ok bool
	if fly, ok = f.flyWeight[key]; !ok {
		fly = FlyWeight{key: key}
		f.flyWeight[key] = fly
	}
	return fly
}

func (f *FactoryFlyWeight) Count() int {
	return len(f.flyWeight)
}

func main() {
	a :=  NewFactoryFlyWeight()
	a.GetFlyWeight("A").Run()
	a.GetFlyWeight("A").Run()
	a.GetFlyWeight("B").Run()
	fmt.Println(a.Count())
}

享元模式优点

  1. 减少对象的创建,提高效率
  2. 缩小内存中对象的数量

享元模式缺点

  1. 使系统更加复杂,需要分离出内部状态和外部状态,使得程序的逻辑更加复杂
  2. 享元对象状态外部化,使运行时间变长

代理模式

为其他对象提供一种代理以控制对这个对象的访问

适用场景

  1. 监控、统计、鉴权、限流等

Go语言实现


type IExecutor interface {
	RunFunc()
}

type SyncExecutor struct {
}

func (e SyncExecutor) RunFunc() {
	time.Sleep(time.Second)
}

type ExecutorProxy struct {
	executor IExecutor
}

func NewExecutorProxy(e IExecutor) *ExecutorProxy {
	return &ExecutorProxy{executor: e}
}

func (e *ExecutorProxy) RunFunc() {
	start := time.Now()
	e.executor.RunFunc()
	fmt.Printf("运行用时: %+v", time.Since(start))
}

func main() {
	a := NewExecutorProxy(proxy.SyncExecutor{})
	a.RunFunc()
}

代理模式优点

  1. 在客户端和目标对象间起到一个中介作用,保护目标对象
  2. 可以扩展目标对象的功能
  3. 将客户端和目标对象分离,降低了系统耦合度,增加了程序的可扩展性

代理模式缺点

  1. 使系统设计中类的数量增多,增加了系统的复杂度
  2. 在客户端和目标对象间增加一个代理对象,请求速度变慢