go設計模式之外觀模式
這篇是設計模式中結構模式的第一篇。微服務架構現在是系統的架構的主流,它將系統拆分成一個個獨立的服務,服務之間通過通訊建立起關聯關係。假設現在有一個部落格的系統,它由四個微服務組成。使用者服務,文章管理服務,分類服務,評論服務。系統的微服務間會發生以下的服務關係。
服務間的呼叫關係比較混亂,微服務架構中通過一個閘道器來解決這種混亂的服務間呼叫,通過閘道器統一對外服務。
看一下改進後的呼叫關係圖。
這樣改進後,呼叫關係就變得清晰明瞭。結構圖中的閘道器就是一個要展開的外觀模式結構。
接下來通過go語言實現這種外觀模式。
package main import "fmt" type Facade struct { UserSvc UserSvc ArticleSvc ArticleSvc CommentSvc CommentSvc } // 使用者登入 func (f *Facade) login(name, password string) int { user := f.UserSvc.GetUser(name) if password == user.password { fmt.Println("登入成功!!!") } return user.id } func (f *Facade) CreateArticle(userId int, title, content string) *Article { articleId := 12345 article := f.ArticleSvc.Create(articleId, title, content, userId) return article } func (f *Facade) CreateComment(articleId int, userId int, comment string) *Comment { commentId := 12345 cm := f.CommentSvc.Create(commentId, comment, articleId, userId) return cm } // 使用者服務 type UserSvc struct { } type User struct { id int name string password string } func (user *UserSvc) GetUser(name string) *User { if name == "zhangsan" { return &User{ id: 12345, name: "zhangsan", password: "zhangsan", } } else { return &User{} } } // 文章服務 type ArticleSvc struct { } type Article struct { articleId int title string content string authorId int } func (articleSvc *ArticleSvc) Create(articleId int, title string, content string, userId int) *Article { return &Article { articleId: articleId, title: title, content: content, authorId: userId, } } // 評論服務 type CommentSvc struct { } type Comment struct { commentId int comment string articleId int userId int } func (commentSvc *CommentSvc) Create(commentId int, comment string, articleId int, userId int)*Comment { return &Comment{ commentId: commentId, comment: comment, articleId: articleId, userId: userId, } } func main() { f := &Facade{} userId := f.login("zhangsan", "zhangsan") fmt.Println("登入成功,當前使用者Id", userId) title := "go設計模式外觀模式" content := "外觀模式是結構模式的一種。。。。" article := f.CreateArticle(userId, title, content) fmt.Println("文章發表成功,文章id", article.articleId) comment := f.CreateComment(article.articleId, userId, "介紹的很詳細") fmt.Println("評論提交成功,評論id", comment.commentId) }複製程式碼