定義:
命令模式:將一個請求封裝為一個對象,從而使你可用冉的請求對客戶進行參數化;對請求排隊或記錄請求日志,以及支持課撤銷的操作。
UML:
命令模式涉及到五個角色,它們分別是:
優點:
實例:
主要實現功能:客戶打算要點兩次烤羊肉,一次烤雞肉。
package com.zcr.Command;
//燒烤人員
public class Barbecuer
{
//烤羊肉
public void BakeMutton()
{
System.out.println("烤羊肉!!");
}
//烤雞翅
public void BakeChickenWing()
{
System.out.println("烤雞翅!!");
}
}
抽象命令類
package com.zcr.Command;
public abstract class Command
{
protected Barbecuer receiver;
public Command()
{
}
public Command(Barbecuer barbecuer)
{
this.receiver = barbecuer;
}
//執行命令
abstract public void ExcuteCommand();
}
具體命令類
package com.zcr.Command;
//烤雞翅命令
public class BakeChickenWingCommand extends Command
{
public BakeChickenWingCommand(Barbecuer barbecuer)
{
//receiver 來自父類
receiver = barbecuer;
}
@Override
public void ExcuteCommand()
{
receiver.BakeChickenWing();
}
}
具體命令類
package com.zcr.Command;
//烤羊肉命令
public class BakeMuttonCommand extends Command
{
public BakeMuttonCommand(Barbecuer barbecuer)
{
//receiver 來自父類
receiver = barbecuer;
}
@Override
public void ExcuteCommand()
{
receiver.BakeMutton();
}
}
服務員類
package com.zcr.Command;
public class Waiter
{
private Command command;
//設置訂單
public void SetOrder(Command command)
{
this.command = command;
}
//通知執行
public void Notify()
{
command.ExcuteCommand();
}
}
package com.zcr.Command;
public class TestCommand
{
public static void main(String[] args)
{
//開店前准備,燒烤店實現就找好了烤肉廚師,服務員和烤肉菜單沒等客戶上門
Barbecuer boy = new Barbecuer();
Command bakeMuttonCommand1 = new BakeMuttonCommand(boy);
Command bakeMuttonCommand2 = new BakeMuttonCommand(boy);
Command bakeChiCommand = new BakeChickenWingCommand(boy);
Waiter girl = new Waiter();
//開門營業,
girl.SetOrder(bakeMuttonCommand1);
girl.Notify();
girl.SetOrder(bakeMuttonCommand2);
girl.Notify();
girl.SetOrder(bakeChiCommand);
girl.Notify();
}
}