- 最終返回的是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 中增加調用,不需要改客戶端。