命令模式(Command)

本文介绍了命令模式的设计原理,通过UML类图展示了各部分之间的关系,并提供了C#与Python两种语言的具体实现代码。该模式中,Invoker负责维护Command,而Command又进一步维护CommandTarget,实现了请求的封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人理解:

Invoker维护Command Command维护CommandTarget


UML类图

代码实现

    public interface ICommand
    {
        void Execute();
    }

    public class Invoker
    {
        private ICommand command;

        public void SetCommand(ICommand command)
        {
            this.command = command;
        }

        public void ExecuteCommand()
        {
            this.command.Execute();
        }
    }

    public class PrintCommand:ICommand
    {
        public CommandTarget target;

        public PrintCommand(CommandTarget target)
        {
            this.target = target;
        }

        public void Execute()
        {
            target.Action();
        }
    }

    public class CommandTarget
    {
        public void Action()
        {
            Console.WriteLine("HAHA...The 18th model in 23...Fuck...Bitch...Shit...");
        }
    }

Python代码实现

class CommandTarget(object):
    name=''

class Dog(CommandTarget):
    pass

class Cat(CommandTarget):
    pass

class Command(object):
    def Execute(self):
        raise NotImplementedError("abstract class")

class RunCommand(Command):
    commandTarget=None
    def __init__(self, commandTarget):
        self.commandTarget=commandTarget
    def Execute(self):
        print self.commandTarget.Name + " is running."

class SitCommand(Command):
    commandTarget=None
    def __init__(self, commandTarget):
        self.commandTarget=commandTarget
    def Execute(self):
        print self.commandTarget.Name + " is sitting."

class CommandHandler(object):
    command=None
    def __init__(self, command):
        self.command=command
    def ExecuteCommand(self):
        self.command.Execute()
    def SetCommand(self, command):
        self.command=command

if __name__ == "__main__":
    dog=Dog()
    dog.Name="dog tom"

    cat=Cat()
    cat.Name="cat jerry"

    sitCommand=SitCommand(cat)
    handler=CommandHandler(sitCommand)
    handler.ExecuteCommand()

    runCommand=RunCommand(dog)
    handler.SetCommand(runCommand)
    handler.ExecuteCommand()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值