How to implement the Facade pattern in Golang?
In Golang, the facade pattern can be implemented by defining a facade class to conceal the complexity of the system and provide a simple interface for external use. Here is a simple implementation example of the facade pattern in Golang:
package main
import "fmt"
// 子系统1
type SubSystem1 struct{}
func (s *SubSystem1) Operation1() {
fmt.Println("SubSystem1: Operation1")
}
// 子系统2
type SubSystem2 struct{}
func (s *SubSystem2) Operation2() {
fmt.Println("SubSystem2: Operation2")
}
// 外观类
type Facade struct {
subSystem1 *SubSystem1
subSystem2 *SubSystem2
}
func NewFacade() *Facade {
return &Facade{
subSystem1: &SubSystem1{},
subSystem2: &SubSystem2{},
}
}
func (f *Facade) Operation() {
fmt.Println("Facade: Operation")
f.subSystem1.Operation1()
f.subSystem2.Operation2()
}
func main() {
// 使用外观类
facade := NewFacade()
facade.Operation()
}
In the above example, we defined two subsystems (SubSystem1 and SubSystem2) with their own set of operations. We then created a facade class where we encapsulated the operations of the subsystems.
In the main function, we utilize a facade class to perform operations. With the facade class, we can conceal the complexity of the subsystem and provide a simple interface for external use.
When running the code above, the output is:
Facade: Operation
SubSystem1: Operation1
SubSystem2: Operation2
By appearance alone, we can carry out complex operations through a simple method call.