将建立指令与实际执行分离
PS5 有特定操作 CPU 指令的实作.ACommand()
、.BCommand()
,如果现在又多了新的特定操作,必须修改PS5{}
,这不符合开闭原则,我们需要有方法满足开闭原则。
package main
import "fmt"
type CPU struct{}
func (CPU) ADoSomething() {
fmt.Println("a do something")
}
func (CPU) BDoSomething() {
fmt.Println("b do something")
}
func (CPU) CDoSomething() {
fmt.Println("c do something")
}
type PS5 struct {
cpu CPU
}
func (p PS5) ACommand() {
p.cpu.ADoSomething()
p.cpu.CDoSomething()
}
func (p PS5) BCommand() {
p.cpu.ADoSomething()
p.cpu.BDoSomething()
}
func main() {
cpu := CPU{}
ps5 := PS5{cpu}
ps5.ACommand()
ps5.BCommand()
}
新增Command
interface,里头有Execute()
这个 function,并实作ACommand{}
、BCommand{}
,让指令的建立从PS5{}
中分离出来,即满足开闭原则。
最後透过PS5{}.SetCommand()
来将符合Command
interface 的指令设定给 PS5,再透过PS5{}.DoCommand()
选择要执行的指令。
package main
import "fmt"
type CPU struct{}
func (CPU) ADoSomething() {
fmt.Println("a do something")
}
func (CPU) BDoSomething() {
fmt.Println("b do something")
}
func (CPU) CDoSomething() {
fmt.Println("c do something")
}
type Command interface {
Execute()
}
type ACommand struct {
cpu CPU
}
func (a ACommand) Execute() {
a.cpu.ADoSomething()
a.cpu.CDoSomething()
}
type BCommand struct {
cpu CPU
}
func (b BCommand) Execute() {
b.cpu.ADoSomething()
b.cpu.BDoSomething()
}
type PS5 struct {
commands map[string]Command
}
func (p *PS5) SetCommand(name string, command Command) {
p.commands[name] = command
}
func (p *PS5) DoCommand(name string) {
p.commands[name].Execute()
}
func main() {
cpu := CPU{}
aCommand := ACommand{cpu}
bCommand := BCommand{cpu}
ps5 := PS5{make(map[string]Command)}
ps5.SetCommand("a", aCommand)
ps5.SetCommand("b", bCommand)
ps5.DoCommand("a")
ps5.DoCommand("b")
}
<<: day26_ARM 在 Server 领域的发展 (上)
Kubernetes 架构 Kubernetes又称之为k8s,其运作种共分层三个架构层面,1. C...
如果想印出1到100的数字,更常的做法是使用for回圈而不是while 例 for i in 1.....
事件 指的是在 DOM 上所发生的事件,换句话是可以是特定的动作被触发後,必须要执行对应的事情。 (...
音乐播放器 虽然 Mac Os , Linux, Windows 都内建了音乐播放器,但他们仍有一些...
二元搜寻BigO(log n) 相较於线性搜寻时间复杂度实在好太多 必须是被排序好的 由於每次对半砍...