1. Simulate the scene
The requirement is to achieve the need for players to have multiple heroes. After deploying the heroes, you only need to click to attack, and you don’t have to care about each hero’s specific attack method!
2099/12/29 14:19:48 Li Xin releases his ultimate move!
2099/12/29 14:19:48 Li Bai releases his ultimate move!
Facade provides a consistent interface for a set of interfaces in a subsystem. This mode defines a high-level interface, which makes this subsystem easier to use.
2. Code implementation
2.1 Hero
package main // Instantiationfunc NewHero() Hero{ return &heroImpl{ LiXin: NewLixinHero(), LiBai: NewLiBaiHero(), } } // Hero abstract behaviortype Hero interface { Attack() error } // Hero Pooltype heroImpl struct { LiXin LixinHero LiBai LiBaiHero } // Unifiedly call all hero attacks and turn them into an attack buttonfunc (h heroImpl) Attack() error { err := () if err!=nil{ return err } err = () if err!=nil{ return err } return nil }
2.2 LiXin
package main import "log" // Li Xin's abstract behaviortype LixinHero interface { Attack() error } // Hero Li Xintype lixinHero struct { } func NewLixinHero() *lixinHero { return &lixinHero{} } // Li Xin's attack methodfunc (l lixinHero) Attack() error { ("Li Xin releases his ultimate move!") return nil }
2.3 LiBai
package main import "log" // Li Bai's abstract behaviortype LiBaiHero interface { Attack() error } // Hero Li Baitype libaiHero struct { } func NewLiBaiHero() *libaiHero { return &libaiHero{} } // Li Bai's attack methodfunc (l libaiHero) Attack() error { ("Li Bai releases his ultimate move!") return nil }
2.4 main
After deployment, one-click attack! !
package main import "log" func main(){ hero:=NewHero() // Deployment phase err:=() // One-click attack if err!=nil{ (err) } }
3. Meaning
From this we can see that the appearance mode is very simple. We only need to attack on the client side. We do not need to pay attention to any operation of the hero inside. For friends who have a certain foundation in object-oriented, even if they have never heard of the appearance mode, it is entirely possible to use it in many cases, because it perfectly reflects the idea of the principle of dependency reversal and the law of Dimit, so it is one of the most commonly used patterns.
There are many situations when we use appearance modes, such as the classic MVC three-layer architecture, which can consider the appearance of resumes between the data access layer and the business logic layer, the business logic layer and the presentation layer to reduce coupling. It blocks the interaction process with the complex internal means, making the outside world easier!
This is the article about the implementation of Golang design mode external appearance mode. For more related Go appearance mode content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!