设计模式-命令模式

设计模式-命令模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1dqdoEYy-1660624725543)(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUJNsM7UWjskq8KUH-3EL9eNWfz-QT-F7akA&usqp=CAU)]

参考


命令模式时一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

使用场景

认为是命令的地方都可以使用命令模式,例如GUI中的按钮,模拟CMD

Demo分析

下面模拟游戏中的一种通用架构:客户端的各种命令请求被服务端存储起来,然后服务器的单线程顺序的去执行这些请求。

Go实现

package main

import "fmt"

/**
* 命令接口
 */
type Command interface {
	Execute()
}

/**
* 移动命令
 */
type MoveCommand struct {
	x, y int
}

func (m *MoveCommand) Execute() {
	fmt.Printf("Move to %d, %d\n", m.x, m.y)
}

/**
* 攻击命令
 */
type AttackCommand struct {
	skill string
}

/**
* 攻击的动作执行
 */
func (a *AttackCommand) Execute() {
	fmt.Printf("Attack with %s\n", a.skill)
}

func AddCommand(action string) Command {
	if action == "attack" {
		return &AttackCommand{skill: "sword"}
	} else {
		return &MoveCommand{x: 1, y: 2}
	}
}

func test() {
	commandList := make([]Command, 0)
	commandList = append(commandList, AddCommand("attack"))
	commandList = append(commandList, AddCommand("move"))
	commandList = append(commandList, AddCommand("attack"))
	for _, c := range commandList {
		c.Execute()
	}
}

func main() {
	test()
}

输出

Attack with sword
Move to 1, 2     
Attack with sword

Python实现

class Command(object):
  """
    ## 命令的接口
  """
  def Execute(self):
    pass

class MoveCommand(Command):
  """
    ## 移动命令
  """
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def Execute(self):
    print(f"Move to {self.x},{self.y}")


class AttackCommand(Command):
  """
    ## 攻击命名
  """
  def __init__(self, skill):
    self.skill = skill
  def Execute(self):
    print(f"Attack with {self.skill}")

def AddCommand(action):
  """
    ## 添加命令
  """
  if action == "attack":
    return AttackCommand("crush")
  else :
    return MoveCommand(1,2)

def test():
  commandList = []
  commandList.append(AddCommand("attack"))
  commandList.append(AddCommand("move"))
  commandList.append(AddCommand("attack"))
  for command in commandList:
    command.Execute()

if __name__ == '__main__':
  test()

输出

Attack with crush
Move to 1,2
Attack with crush

小结

感觉命令模式与工厂模式类似,感觉不同的是命令模式强调的是生成一种动作的对象,生成的一系列的对象用于动作的执行。同时可以延时去执行动作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值