命令模式
命令模式
命令接口
package command
type command interface {
    Execute()
}
命令执行者
package command
func NewSystem() *system {
	return &system{}
}
func (s *system) OpenFile() {
	fmt.Println("打开记事本文件")
}
func (s *system) EditFile() {
	fmt.Println("编辑文件")
}
func (s *system) SaveFile() {
	fmt.Println("保存文件")
}
func (s *system) CloseFile() {
	fmt.Println("关闭文件")
}
编辑命令
package command
type edit struct {
	sys *system
}
func NewEdit(sys *system) command {
	return &edit{sys: sys}
}
func (e *edit) Execute() {
	e.sys.OpenFile()
	e.sys.EditFile()
	e.sys.SaveFile()
	e.sys.CloseFile()
}
查看命令
package command
type search struct {
	sys *system
}
func NewSearch(sys *system) command {
	return &search{sys: sys}
}
func (s *search) Execute() {
	s.sys.OpenFile()
	s.sys.CloseFile()
}
命令发出者
package command
import "fmt"
type invoke struct {
	commands []command
}
func NewInvoke() *invoke {
	return &invoke{
		commands: make([]command, 0),
	}
}
func (i *invoke) AddCommand(cmd command) {
	i.commands = append(i.commands, cmd)
}
func (i *invoke) Do() {
	for _, v := range i.commands {
		fmt.Println("**********************************")
		if v == nil {
			return
		}
		v.Execute()
	}
}
测试文件
package command
func TestCommand(t *testing.T) {
    sys := NewSystem()
	e := NewEdit(sys)
	s := NewSearch(sys)
	p := NewInvoke()
	p.AddCommand(e)
	p.AddCommand(s)
	p.Do()
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号