无废话设计模式(18)行为型模式--命令模式

0-前言

  命令模式定义(Command):

    将一个请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化;

    对请求排队或记录请求日志,以及支持可撤销的操作;

1-实现

1-1、简单UML图

 

 

1-2、代码实现

//1、命令执行者(Receiver--小兔崽子)
class Son
{
    //做饭
    public void Cooking()
    {
        System.out.println("小兔崽子乖乖做饭去了");
    }
    //喂猪
    public void FeedPigs()
    {
        System.out.println("小兔崽子乖乖喂猪去了");
    }
}

//2、命令抽象父类(Command)
abstract class  Command
{
    //设置命令执行者
    protected Son son;
    public Command(Son _son)
    {
        this.son = _son;
    }

    //执行命令
    public  abstract void  Execute();
}

//2-1、具体命令A(做饭)
class CommandCooking extends Command
{
    public CommandCooking(Son _son)
    {
        super(_son);
    }

    //执行命令

    @Override
    public void Execute()
    {
        son.Cooking();
    }
}

//2-2、具体命令B(喂猪)
class CommandFeedpigs extends Command
{
    public CommandFeedpigs(Son _son)
    {
        super(_son);
    }

    //执行命令

    @Override
    public void Execute()
    {
        son.FeedPigs();
    }
}

//3、命令传达者(Invoker---老爹)
class  Father
{
    private Command command;
    //A、设置命令
    public void setCommand(Command command)
    {
        this.command = command;
    }

    //B、要求执行命令
    public void Doing()
    {
        command.Execute();
    }

 

客户端

        Son son = new Son();
        Command cooking = new CommandCooking(son);
        Command feedpigs = new CommandFeedpigs(son);

        Father father = new Father();
        //做饭
        father.setCommand(cooking);
        father.Doing();
        //喂猪
        father.setCommand(feedpigs);
        father.Doing();

 

运行结果

 

 

2-应用场景简单总结

1、当需要抽象出需要执行的动作以便参数化某个对象时;

2、当需要在不同的时候执行、排列、执行请求时;

3、当系统需要支持取消操作时;

4、当系统需要记录、修改日志时;

posted @ 2020-08-07 11:09  程序员恒哥  阅读(217)  评论(0编辑  收藏  举报