内容简介:这篇是设计模式中结构模式的第一篇。微服务架构现在是系统的架构的主流,它将系统拆分成一个个独立的服务,服务之间通过通信建立起关联关系。假设现在有一个博客的系统,它由四个微服务组成。用户服务,文章管理服务,分类服务,评论服务。系统的微服务间会发生以下的服务关系。服务间的调用关系比较混乱,微服务架构中通过一个网关来解决这种混乱的服务间调用,通过网关统一对外服务。
这篇是 设计模式 中结构模式的第一篇。微服务架构现在是系统的架构的主流,它将系统拆分成一个个独立的服务,服务之间通过通信建立起关联关系。假设现在有一个博客的系统,它由四个微服务组成。用户服务,文章管理服务,分类服务,评论服务。系统的微服务间会发生以下的服务关系。
服务间的调用关系比较混乱,微服务架构中通过一个网关来解决这种混乱的服务间调用,通过网关统一对外服务。
看一下改进后的调用关系图。
这样改进后,调用关系就变得清晰明了。结构图中的网关就是一个要展开的外观模式结构。
接下来通过 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)
}复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 设计模式——订阅模式(观察者模式)
- 设计模式-简单工厂、工厂方法模式、抽象工厂模式
- java23种设计模式-门面模式(外观模式)
- 设计模式-享元设计模式
- Java 设计模式之工厂方法模式与抽象工厂模式
- JAVA设计模式之模板方法模式和建造者模式
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Android和PHP开发最佳实践
黄隽实 / 机械工业出版社华章公司 / 2013-3-20 / 79.00元
本书是国内第一本同时讲述Android客户端开发和PHP服务端开发的经典著作。 本书以一个完整的微博应用项目实例为主线,由浅入深地讲解了Android客户端开发和PHP服务端开发的思路和技巧。从前期的产品设计、架构设计,到客户端和服务端的编码实现,再到性能测试和系统优化,以及最后的打包发布,完整地介绍了移动互联网应用开发的过程。同时,本书也介绍了Android系统中比较有特色的功能,比如Go......一起来看看 《Android和PHP开发最佳实践》 这本书的介绍吧!
URL 编码/解码
URL 编码/解码
RGB HSV 转换
RGB HSV 互转工具