1. 程式人生 > >命令模式(1)

命令模式(1)

oid .exe face ntc info nts () receiver clas

命令模式的四種角色:

1、接受者(Receiver)負責執行請求的相關操作的一個類

2、命令接口:(Command)用於封裝請求的方法

3、具體命令:(ConcreteCommand)命令接口的具體實現類

4、請求者:(Invoker)包含了命令接口的實例變量,負責調用具體命令

技術分享圖片

請求者:
package DesignPatterns.CommandMode;

public class Invoker {
    private Command command;

    public void setCommand(Command command) {
        
this.command = command; } public void startCommand(){ command.execute(); } }
命令接口:
package DesignPatterns.CommandMode;

public interface Command {
    public void execute();
}

具體命令:
package DesignPatterns.CommandMode;

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


}

接受者:

package DesignPatterns.CommandMode;

public class Receiver {
public void printCommand()
{
System.out.println("執行命令");
}

}


測試類:

package DesignPatterns.CommandMode;

public class Application {
public static void main(String[] args)
{
Receiver receiver=new Receiver();
Command command=new ConcreteCommand(receiver);
Invoker invoker=new Invoker();
invoker.setCommand(command);
invoker.startCommand();

}
}


命令模式(1)