Big talk design mode-command mode

1. Command mode: Encapsulate a request as an object, so that you can parameterize clients with different requests; queue or log request logs, and support undoable operations

Second, the code example:

public class Barbecue {

    public void bakeMutton(){
        System.out.println("烤羊肉串");
    }

    public void bakeChickenWing(){
        System.out.println("烤鸡翅");
    }
}

public abstract class Command {
    protected Barbecue receiver;

    public Command(Barbecue receiver) {
        this.receiver = receiver;
    }

    abstract public void excuteCommand();
}

public class BakeChickenWingCommand extends Command {

    public BakeChickenWingCommand(Barbecue receiver) {
        super(receiver);
    }

    @Override
    public void excuteCommand() {
        receiver.bakeChickenWing();
    }
}

public class BakeMuttonCommand extends Command {

    public BakeMuttonCommand(Barbecue receiver) {
        super(receiver);
    }

    @Override
    public void excuteCommand() {
        receiver.bakeMutton();
    }
}

public class Waiter { 

    private List <Command> orders = new ArrayList <> (); 

    public  void setOrder (Command command) {
         if (command instanceof BakeChickenWingCommand) { 
            System.out.println ( "Attendant: Chicken wings are gone, please order another barbecue " ); 
        } Else { 
            orders.add (command); 
            System.out.println ( " Add order: "+ command.toString () +" Time "+ new Date ()); 
        } 
    } 

    public  void cancleOrder (Command command ) {  
        orders.remove (command);
        System.out.println ("取消订单" + command.toString() + "时间" + new Date());
    }

    public void notice(){
        orders.forEach(Command::excuteCommand);
    }
}

public class Main {
    public static void main(String[] args) {
        Barbecue boy = new Barbecue();
        Command bakeMuttonCommand1 = new BakeMuttonCommand(boy);
        Command bakeMuttonCommand2 = new BakeMuttonCommand(boy);
        Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy);

        Waiter girl = new Waiter();
        girl.setOrder(bakeMuttonCommand1);
        girl.setOrder(bakeMuttonCommand2);
        girl.setOrder(bakeChickenWingCommand1);

        girl.notice();
    }
}

Three, advantages

  1. Can easily design a command queue

  2. If necessary, you can easily log the command to the log

  3. Allow the receiving party to decide whether to reject the request

  4. Can undo and redo the request easily

  5. Since the newly added specific command classes do not affect other classes, it is easy to add new specific command classes

 The principles of agile development tell us not to add guess-based features that are not actually needed to the code. It can be refactored when needed.

Guess you like

Origin www.cnblogs.com/zsmcwp/p/12694657.html