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)
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章