内容简介:这篇是设计模式中结构模式的第一篇。微服务架构现在是系统的架构的主流,它将系统拆分成一个个独立的服务,服务之间通过通信建立起关联关系。假设现在有一个博客的系统,它由四个微服务组成。用户服务,文章管理服务,分类服务,评论服务。系统的微服务间会发生以下的服务关系。服务间的调用关系比较混乱,微服务架构中通过一个网关来解决这种混乱的服务间调用,通过网关统一对外服务。
这篇是 设计模式 中结构模式的第一篇。微服务架构现在是系统的架构的主流,它将系统拆分成一个个独立的服务,服务之间通过通信建立起关联关系。假设现在有一个博客的系统,它由四个微服务组成。用户服务,文章管理服务,分类服务,评论服务。系统的微服务间会发生以下的服务关系。
服务间的调用关系比较混乱,微服务架构中通过一个网关来解决这种混乱的服务间调用,通过网关统一对外服务。
看一下改进后的调用关系图。
这样改进后,调用关系就变得清晰明了。结构图中的网关就是一个要展开的外观模式结构。
接下来通过 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)
}复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
高质量程序设计艺术
斯皮内利斯 / 韩东海 / 人民邮电出版社 / 2008-1 / 55.00元
在本书中,作者回归技术层面。从Apache web server、BSD版本的Unix system、ArgoUMl、ACE网络编程库等著名开源软件中选取了大量真实C、C++和java语言源代码,直观而深刻的阐述了代码中可能存在的各种质量问题,涉及可靠性、安全性、时间性和空间性、可移植性、可维护性以及浮点运算等方面,很多内容都市独辟蹊径,发前人所未发。正因如此,本书继作者的《代码阅读》之后在获Jo......一起来看看 《高质量程序设计艺术》 这本书的介绍吧!