11.Golang设计模式之外观模式

ShawnLee_123 · · 493 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

外观模式

GitHub代码链接
外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问的接口。

什么是外观模式

外观模式为子系统中的一组接口提供一个一致的界面,这个接口使得这一子系统更加容易使用。

解决了什么问题

降低子系统访问的复杂性,简化客户端与子系统之间的接口。

优点

  • 减少系统间的相互依赖
  • 提高灵活性
  • 提高安全性

缺点

  • 不符合开闭原则

代码实现

创建三个模型实例,使用一个外观类来包含这三个模型实例,使得用户可以通过外观类使用统一的接口来调用这三个模型实例。

1.1 模型实例创建

//Shape 模型接口
type Shape interface {
    Draw()
}

//Circle 圆形类
type Circle struct{}

//Rectangle 矩形类
type Rectangle struct{}

//Square 正方形类
type Square struct{}

//NewCircle 实例化圆形类
func NewCircle() *Circle {
    return &Circle{}
}

//Draw 实现Shape接口
func (c *Circle) Draw() {
    fmt.Println("Circle Draw method.")
}

1.2 外观类实现

//ShapeMaker 外观类
type ShapeMaker struct {
    circle    Circle
    square    Square
    rectangle Rectangle
}

//NewShapeMaker 实例化外观类
func NewShapeMaker() *ShapeMaker {
    return &ShapeMaker{
        circle:    Circle{},
        rectangle: Rectangle{},
        square:    Square{},
    }
}

//DrawCircle 调用circle的Draw方法
func (shapeMk *ShapeMaker) DrawCircle() {
    shapeMk.circle.Draw()
}

//DrawRectangle 调用rectangle的Draw方法
func (shapeMk *ShapeMaker) DrawRectangle() {
    shapeMk.rectangle.Draw()
}

//DrawSquare 条用square的Draw方法
func (shapeMk *ShapeMaker) DrawSquare() {
    shapeMk.square.Draw()
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:ShawnLee_123

查看原文:11.Golang设计模式之外观模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

493 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传