Golang设计模式之外观模式

来源:互联网 发布:php判断水仙花数 编辑:程序博客网 时间:2024/06/05 07:40

1. 概述

它为一套复杂的调度子系统提供一个统一的接入接口。外部所有对子系统的调用都通过这个外观角色进行统一调用,降低子系统与调用者之间的耦合度。
Golang设计模式相关源码在github上有提供,可供参考!

2. 举例说明

那当前比较热门的微服务来说,一套服务(比如说短视频服务)包括若干子服务,如图(a),如:音乐服务,短视频服务,计数服务,推荐子服务等。客户端不同的请求会使用不同的子服务。客户端视频创作会请求音乐素材,视频上传服务;浏览推荐视频需要请求视频推荐服务和计数服务。这种情况下,我们可以引入一个统一的gateway层作为外观模式,统一管理入口, 如图(b)。

before

图(a)

after

图(b)

3. 外观模式类图

4. Go语言实现示例

type Facade struct {    M Music    V Video    C Count}func (this *Facade) GetRecommandVideos() error {    this.V.GetVideos()    this.C.GetCountByID(111)    return nil}type Music struct {}func (this *Music) GetMusic() error {    fmt.Println("get music material")    // logic code here    return nil}type Video struct {    vid int64}func (this *Video) GetVideos() error {    fmt.Println("get videos1")    return nil}type Count struct {    PraiseCnt  int64 //点赞数    CommentCnt int64 //评论数    CollectCnt int64 //收藏数}func (this *Count) GetCountByID(id int64) (*Count, error) {    fmt.Println("get video counts")    return this, nil}func main() {    f := &Facade{}    f.GetRecommandVideos()}
原创粉丝点击