外观模式(Facade Pattern)是一种结构型设计模式,它提供了一个简化系统接口的高层接口,使得系统更易于使用。外观模式定义了一个高层接口,这个接口隐藏了系统中多个子系统的复杂性,为客户端提供了一个简化的入口点。
考虑一个计算机启动的例子。在一个计算机启动的过程中,涉及到多个子系统的初始化,例如 CPU、内存、硬盘等。使用外观模式可以封装这些子系统的初始化过程,为客户端提供一个简化的接口。
package main
import "fmt"
// Subsystem1
type CPU struct{}
func (c *CPU) Start() {
fmt.Println("CPU is starting")
}
// Subsystem2
type Memory struct{}
func (m *Memory) Load() {
fmt.Println("Memory is loading")
}
// Subsystem3
type HardDrive struct{}
func (h *HardDrive) Read() {
fmt.Println("Hard Drive is reading")
}
// Facade
type ComputerFacade struct {
cpu *CPU
memory *Memory
hardDrive *HardDrive
}
func NewComputerFacade() *ComputerFacade {
return &ComputerFacade{
cpu: &CPU{},
memory: &Memory{},
hardDrive: &HardDrive{},
}
}
func (f *ComputerFacade) Start() {
fmt.Println("Computer is starting...")
f.cpu.Start()
f.memory.Load()
f.hardDrive.Read()
fmt.Println("Computer is started")
}
// Client
func main() {
computer := NewComputerFacade()
computer.Start()
}
在这个示例中,ComputerFacade
封装了启动计算机所需的多个子系统,包括 CPU、Memory、HardDrive。客户端只需要与 ComputerFacade
交互,而无需了解启动过程中各个子系统的具体细节。这样简化了客户端的使用,同时提高了系统的可维护性。
我正在参与2024腾讯技术创作特训营第五期有奖征文,快来和我瓜分大奖!
声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意
腾讯云开发者社区:孟斯特
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。