- 最终返回的是Document的切片,然后取得Bytes自己再去做反序列化拿到文档的各种详细信息。
- 外观模式是一种结构型设计模式,它的目的是为复杂的子系统提供一个统一的高层接口,让外部调用者(客户端)可以更简单地使用子系统,而不需要了解子系统内部的细节。
- 动机:当系统内部有很多复杂的模块、接口时,直接使用会非常麻烦。外观模式可以对外提供一个简化接口,让客户端可以很容易地访问系统的功能。
- 核心作用:封装复杂性,提供简单接口。
- 特点:
- 降低子系统之间的耦合度
- 客户端只需要跟外观对象交互
- 不影响子系统内部功能的扩展
// 外观模式结构图+----------------+| Client |+--------+--------+|v+--------+--------+| Facade | (外观类,统一对外接口)+--------+--------+|+------------------+------------------+| | |v v v
+------------+ +--------------+ +--------------+
| SubSystem1 | | SubSystem2 | | SubSystem3 |
| (Power) | | (HardDrive) | | (OperatingSys)|
+------------+ +--------------+ +--------------+
// 电脑开机示例package mainimport "fmt"// 子系统:电源管理
type Power struct{}func (p *Power) On() {fmt.Println("Power is ON.")
}
func (p *Power) Off() {fmt.Println("Power is OFF.")
}// 子系统:硬盘管理
type HardDrive struct{}func (h *HardDrive) ReadData() {fmt.Println("HardDrive is reading data.")
}// 子系统:操作系统管理
type OperatingSystem struct{}func (os *OperatingSystem) Boot() {fmt.Println("Operating System is booting up.")
}
func (os *OperatingSystem) Shutdown() {fmt.Println("Operating System is shutting down.")
}// 外观(Facade)
type ComputerFacade struct {power *PowerhardDrive *HardDriveos *OperatingSystem
}// 创建外观对象
func NewComputerFacade() *ComputerFacade {return &ComputerFacade{power: &Power{},hardDrive: &HardDrive{},os: &OperatingSystem{},}
}// 开机流程
func (c *ComputerFacade) Start() {fmt.Println("Starting the computer...")c.power.On()c.hardDrive.ReadData()c.os.Boot()fmt.Println("Computer is ready to use.")
}// 关机流程
func (c *ComputerFacade) Shutdown() {fmt.Println("Shutting down the computer...")c.os.Shutdown()c.power.Off()fmt.Println("Computer is turned off.")
}func main() {computer := NewComputerFacade()computer.Start()fmt.Println()computer.Shutdown()
}Starting the computer...
Power is ON.
HardDrive is reading data.
Operating System is booting up.
Computer is ready to use.Shutting down the computer...
Operating System is shutting down.
Power is OFF.
Computer is turned off.
- 子系统 Power、HardDrive、OperatingSystem 提供各自复杂的功能。
- ComputerFacade 封装了子系统的调用顺序,提供了简单的 Start() 和 Shutdown() 方法。
- 外部调用者(main函数)只需要关心 ComputerFacade,不需要了解具体步骤。
- 外观模式 = 复杂系统的门面 ➔ 把一堆子系统打包成一个简单接口,统一对外提供服务。
- 隐藏复杂性:客户端不用知道各个子系统的复杂调用过程。
- 降低耦合:客户端只依赖外观类,子系统改了也不会直接影响客户端。
- 更清晰的结构:便于维护和扩展,比如以后增加“自检模块”,只需要在 Facade 中增加调用,不需要改客户端。