命令模式

2019-05-07  本文已影响0人  Davisxy

介绍

小栗子

package com.principle.command;

/**
 * 真正的执行者
 * @author xy
 *
 */
public class Receiver {
    public void action(){
        System.out.println("Receiver.action()");
    }
}
package com.principle.command;

public interface Command {
    /**
     * 这个方法是一个返回结果为空的方法
     * 实际项目中,可以根据需求设计做个不同的方法
     */
    void execute();
}

class ConcreteCommand implements Command{
    
    private Receiver receiver;
    
    public ConcreteCommand(Receiver receiver) {
        super();
        this.receiver = receiver;
    }



    @Override
    public void execute() {
        receiver.action();
    }
    
}
package com.principle.command;

import java.util.List;


/**
 * 调用者/发起者
 * @author xy
 *
 */
public class Invoke {
    
    private List<Command> commands;

    public Invoke(List<Command> commands) {
        super();
        this.commands = commands;
    }
    
    //业务方法,用于调用命令类的方法
    public void call(){
        for (Command command : this.commands) {
            command.execute();
        }
    }

}
package com.principle.command;

import java.util.ArrayList;
import java.util.List;


public class Client {
    public static void main(String[] args) {
        Command command1=new ConcreteCommand(new Receiver());
        Command command2=new ConcreteCommand(new Receiver());
        Command command3=new ConcreteCommand(new Receiver());
        List<Command> list=new ArrayList<Command>();
        list.add(command1);
        list.add(command2);
        list.add(command3);
        
        Invoke invoke=new Invoke(list);
        invoke.call();
    }
}
控制台输出:
Receiver.action()
Receiver.action()
Receiver.action()

类图

命令者模式.png
上一篇 下一篇

猜你喜欢

热点阅读