[設計模式練習]命令模式
到銀行存錢跟領錢用命令模式去設計
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.命令
{
/// <summary>
/// command類別
/// </summary>
public abstract class Command
{
protected Banker banker;
public Command(Banker banker)
{
this.banker = banker;
}
abstract public void LoanOrSaveMoney();
}
/// <summary>
/// ConcreteCommand類別:借錢
/// </summary>
class LoanMoney : Command
{
public LoanMoney(Banker banker) : base(banker) { }
public override void LoanOrSaveMoney()
{
banker.LoanMoney();
}
}
/// <summary>
/// ConcreteCommand類別:存錢
/// </summary>
class SaveMoney : Command
{
public SaveMoney(Banker banker) : base(banker) { }
public override void LoanOrSaveMoney()
{
banker.SaveMoney();
}
}
/// <summary>
/// Invoker類別:業務員
/// </summary>
public class AO
{
private List<Command> command = new List<Command>();
/// <summary>
/// 新增業務.
/// </summary>
/// <param name="command">The command.</param>
public void SetCommand(Command command)
{
this.command.Add(command);
Console.WriteLine("增加業務:{0}\t{1}", command.ToString(), DateTime.Now.ToString());
}
/// <summary>
/// 取消業務.
/// </summary>
/// <param name="command">The command.</param>
public void CancelCommand(Command command)
{
this.command.Remove(command);
Console.WriteLine("取消業務:{0}\t{1}", command.ToString(), DateTime.Now.ToString());
}
/// <summary>
/// 通知全部執行.
/// </summary>
public void Notify()
{
foreach (Command tempcmd in command)
{
tempcmd.LoanOrSaveMoney();
}
}
}
/// <summary>
/// Receiver類別:銀行員
/// </summary>
public class Banker
{
public void LoanMoney()
{
Console.WriteLine("借錢");
}
public void SaveMoney()
{
Console.WriteLine("存錢");
}
}
}
用戶端程式碼
//初始化
DesignModelTest.命令.Banker banker = new DesignModelTest.命令.Banker();
//使concrete command類別和receiver連繫
DesignModelTest.命令.Command commandLoan = new DesignModelTest.命令.LoanMoney(banker);
DesignModelTest.命令.Command commandSave = new DesignModelTest.命令.SaveMoney(banker);
DesignModelTest.命令.AO ao = new DesignModelTest.命令.AO();
//增加命令序列
ao.SetCommand(commandLoan);
ao.SetCommand(commandSave);
ao.CancelCommand(commandLoan);
//執行業務
ao.Notify();
Console.Read();
#endregion
輸出結果