Skip to content
← 返回设计模式列表
设计意图与对象责任

外观 ​

给复杂子系统提供简单入口。

结构型

说明 ​

把一连串常见操作收在单个 API 内,减少调用方对内部步骤的了解。

分析 ​

Service.Register 把保存数据和发送通知组合成一个有意义的业务操作。调用方无需知道两个子系统的调用顺序,后续调整流程也集中在外观对象内。

Register 把保存和通知串成入口,但示例 Save 与 Notify 都为空实现,只说明顺序。真实存储成功而通知失败时,需要记录待重试通知或采用事务性发件箱等明确方案,外观对象不会自动把两个系统变为原子操作。对外应说明失败发生在哪一步以及调用方能否重试。

查看图表代码

适用前提与边界 ​

外观可以简化常见操作,但应保留必要的底层能力供特殊场景使用。 只有接口适配或独立变化确实存在时,才增加额外包装层。

示例输入与调用 ​

go
service := Service{}
	service.Register("Ada")
	fmt.Println("registered Ada")

运行输出 ​

text
registered Ada

完整 Go 示例 ​

go
package main

import "fmt"

type Store struct{}

func (Store) Save(string) {

}

type Notifier struct{}

func (Notifier) Notify(string) {

}

type Service struct {
	Store    Store
	Notifier Notifier
}

func (s Service) Register(name string) {
	s.Store.Save(name)
	s.Notifier.Notify(name)
}

func main() {
	service := Service{}
	service.Register("Ada")
	fmt.Println("registered Ada")
}

继续阅读