22、Command 命令模式

1command

Command Pattern使 使

便使()

()

使

使"/"""""

2

2.1

 
 //  
 class Adder {  
     private int num=0; //0  
 
     //num  
     public int add(int value) {  
         num += value;  
         return num;  
    }  
 }  
 
 //  
 abstract class AbstractCommand {  
     public abstract int execute(int value); //execute()  
     public abstract int undo(); //undo()  
 }  
 
 //  
 class ConcreteCommand extends AbstractCommand {  
     private Adder adder = new Adder();  
     private int value;  
 
     //execute()   
public int execute(int value) {   
        this.value=value;   
        return adder.add(value);   
   }    

    //undo()   
    public int undo() {   
        return adder.add(-value);   
   }   
}    

//   
class CalculatorForm {   
    private AbstractCommand command;    

    public void setCommand(AbstractCommand command) {   
        this.command = command;   
   }    

    //execute()   
    public void compute(int value) {   
        int i = command.execute(value);   
        System.out.println("" + i);   
   }    

    //undo()   
    public void undo() {   
        int i = command.undo();   
        System.out.println("" + i);   
   }   
}

 class Client {  
    public static void main(String args[]) {  
        CalculatorForm form = new CalculatorForm();  
        AbstractCommand command;  
        command = new ConcreteCommand();  
        form.setCommand(command); //  
 
        form.compute(10);  
        form.compute(5);  
        form.compute(10);  
        form.undo();  
    }  
 }

 10
 15
 25
 15

2.2

CommandQueueCommandQueue

 import java.util.*;  
 
 class CommandQueue {  
    //ArrayList  
    private ArrayList<Command> commands = new ArrayList<Command>();  
 
    public void addCommand(Command command) {  
        commands.add(command);  
    }  
 
    public void removeCommand(Command command) {  
        commands.remove(command);  
    }  
 
    //execute()  
    public void execute() {  
        for (Object command : commands) {  
            ((Command)command).execute();  
        }  
    }  
 }

CommandQueueInvokerCommandQueue

 class Invoker {  
    private CommandQueue commandQueue; //CommandQueue  
 
    //  
    public Invoker(CommandQueue commandQueue) {  
        this. commandQueue = commandQueue;  
    }  
 
    //  
    public void setCommandQueue(CommandQueue commandQueue) {  
        this.commandQueue = commandQueue;  
    }  
 
    //CommandQueueexecute()  
    public void call() {  
        commandQueue.execute();  
    }  
 }

使线execute()

3command

Commandexecute()

ConcreteCommandexecute()(Action)

Invokerexecute()

Receiver

使

4

1

2使java使

3使使

12

使

使使1GUI 2 CMD

 

参考于 https://gof.quanke.name/

公众号发哥讲

这是一个稍偏基础和偏技术的公众号,甚至其中包括一些可能阅读量很低的包含代码的技术文,不知道你是不是喜欢,期待你的关注。

img

如果你觉得文章还不错,就请点击右上角选择发送给朋友或者转发到朋友圈~

● 扫码关注我们

据说看到好文章不推荐的人,服务器容易宕机!

本文版权归发哥讲博客园共有,原创文章,未经允许不得转载,否则保留追究法律责任的权利。

 

 

posted @ 2020-08-06 15:17  发哥讲Java  阅读(284)  评论(1编辑  收藏  举报