Golang面试宝典——Go语言实现23种设计模式之结构型模式(下)

使用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. 在客户端和目标对象间增加一个代理对象,请求速度变慢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是几种常见的Golang设计模式: 1. 工厂模式(Factory Pattern):用于创建对象的模式,通过定义一个创建对象的接口来实现对象的实例化。 ```go type Shape interface { Draw() } type Circle struct{} func (c *Circle) Draw() { fmt.Println("Drawing a circle") } type Rectangle struct{} func (r *Rectangle) Draw() { fmt.Println("Drawing a rectangle") } type ShapeFactory struct{} func (sf *ShapeFactory) GetShape(shapeType string) Shape { if shapeType == "circle" { return &Circle{} } else if shapeType == "rectangle" { return &Rectangle{} } return nil } func main() { factory := &ShapeFactory{} circle := factory.GetShape("circle") circle.Draw() // 输出:Drawing a circle rectangle := factory.GetShape("rectangle") rectangle.Draw() // 输出:Drawing a rectangle } ``` 2. 单例模式(Singleton Pattern):确保一个类只有一个实例,并提供一个全局访问点。 ```go type Singleton struct{} var instance *Singleton func GetInstance() *Singleton { if instance == nil { instance = &Singleton{} } return instance } func main() { singleton1 := GetInstance() singleton2 := GetInstance() fmt.Println(singleton1 == singleton2) // 输出:true } ``` 3. 观察者模式(Observer Pattern):定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。 ```go type Subject struct { observers []Observer } func (s *Subject) Attach(observer Observer) { s.observers = append(s.observers, observer) } func (s *Subject) Notify() { for _, observer := range s.observers { observer.Update() } } type Observer interface { Update() } type ConcreteObserver struct{} func (co *ConcreteObserver) Update() { fmt.Println("Observer is updated") } func main() { subject := &Subject{} observer := &ConcreteObserver{} subject.Attach(observer) subject.Notify() // 输出:Observer is updated } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

请叫我雯子小姐的小爷

是雯子吖

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值