/// <summary> /// Receiver Class /// 命令模式 Command Pattern 亦称: 动作、事务、Action、Transaction、Command /// geovindu,Geovin Du eidt /// </summary> public class Game { /// <summary> /// 游戏名称 /// </summary> string gameName; /// <summary> /// /// </summary> /// <param name="name">输入名称</param> public Game(string name) { this.gameName = name; } /// <summary> /// 开始 /// </summary> public void Start() { Console.WriteLine($"{gameName} 开始."); } /// <summary> /// 显示比分 /// </summary> public void DisplayScore() { Console.WriteLine("比分随时在变化."); } /// <summary> /// 完成 /// </summary> public void Finish() { Console.WriteLine($"---游戏: {gameName} 完成结束.---"); } } /// <summary> /// The command interface /// </summary> public interface ICommand { //To execute a command /// <summary> /// 执行 /// </summary> void Execute(); //To undo last command execution /// <summary> /// 结束 /// </summary> void Undo(); } /// <summary> /// GameStartCommand /// 开始命令 /// </summary> public class GameStartCommand : ICommand { /// <summary> /// 游戏 /// </summary> private Game game; /// <summary> /// 开始运行 /// </summary> /// <param name="game"></param> public GameStartCommand(Game game) { this.game = game; } /// <summary> /// 执行 /// </summary> public void Execute() { game.Start(); game.DisplayScore(); } /// <summary> /// 卸载 /// </summary> public void Undo() { Console.WriteLine("取消起动命令."); game.Finish(); } } /// <summary> /// GameStopCommand /// 停止游戏命令 /// </summary> public class GameStopCommand : ICommand { /// <summary> /// /// </summary> private Game game; /// <summary> /// /// </summary> /// <param name="game"></param> public GameStopCommand(Game game) { this.game = game; } /// <summary> /// /// </summary> public void Execute() { Console.WriteLine("完成游戏."); game.Finish(); } /// <summary> /// /// </summary> public void Undo() { Console.WriteLine("取消停止命令."); game.Start(); game.DisplayScore(); } } /// <summary> /// Invoker class /// 遥控 /// </summary> public class RemoteControl { /// <summary> /// /// </summary> ICommand commandToBePerformed, lastCommandPerformed; /// <summary> /// /// </summary> /// <param name="command"></param> public void SetCommand(ICommand command) { this.commandToBePerformed = command; } /// <summary> /// /// </summary> public void ExecuteCommand() { commandToBePerformed.Execute(); lastCommandPerformed = commandToBePerformed; } /// <summary> /// /// </summary> public void UndoCommand() { //Undo the last command executed lastCommandPerformed.Undo(); } }
/// <summary> /// 命令模式 Command Pattern 亦称: 动作、事务、Action、Transaction、Command /// geovindu,Geovin Du eidt /// </summary> public class BankAccount { public int Balance; } /// <summary> /// /// </summary> public class FunctionalCommand { /// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="amount"></param> public void Deposit(BankAccount account, int amount) { account.Balance += amount; } /// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="amount"></param> public void Withdraw(BankAccount account, int amount) { if (account.Balance >= amount) { account.Balance -= amount; Console.WriteLine($"{account.Balance}:{amount}"); } else { account.Balance = amount; Console.WriteLine($"{account.Balance}:{amount}"); } } /// <summary> /// /// </summary> public FunctionalCommand() { var ba = new BankAccount(); var commands = new List<Action>(); commands.Add(() => Deposit(ba, 100)); commands.Add(() => Withdraw(ba, 100)); commands.ForEach(c => c()); } }
/// <summary> /// 命令模式 Command Pattern 亦称: 动作、事务、Action、Transaction、Command /// geovindu,Geovin Du eidt /// </summary> public class BankAccount { /// <summary> /// /// </summary> private int balance; /// <summary> /// /// </summary> private readonly int overdraftLimit = -500; /// <summary> /// /// </summary> /// <param name="balance"></param> public BankAccount(int balance = 0) { this.balance = balance; } /// <summary> /// /// </summary> /// <param name="amount"></param> public void Deposit(int amount) { balance += amount; Console.WriteLine($"Deposited ${amount}, balance is now {balance}"); } /// <summary> /// /// </summary> /// <param name="amount"></param> /// <returns></returns> public bool Withdraw(int amount) { if (balance - amount >= overdraftLimit) { balance -= amount; Console.WriteLine($"Withdrew ${amount}, balance is now {balance}"); return true; } return false; } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return $"{nameof(balance)}: {balance}"; } } /// <summary> /// /// </summary> public interface ICommand { void Call(); void Undo(); bool Success { get; set; } } /// <summary> /// /// </summary> public class BankAccountCommand : ICommand { /// <summary> /// /// </summary> private readonly BankAccount account; /// <summary> /// /// </summary> public enum Action { Deposit, Withdraw } /// <summary> /// /// </summary> private readonly Action action; /// <summary> /// /// </summary> private readonly int amount; /// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="action"></param> /// <param name="amount"></param> public BankAccountCommand(BankAccount account, Action action, int amount) { this.account = account; this.action = action; this.amount = amount; } /// <summary> /// /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> public void Call() { switch (action) { case Action.Deposit: account.Deposit(amount); Success = true; break; case Action.Withdraw: Success = account.Withdraw(amount); break; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> public void Undo() { if (!Success) return; switch (action) { case Action.Deposit: account.Withdraw(amount); break; case Action.Withdraw: account.Deposit(amount); break; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// /// </summary> public bool Success { get; set; } } /// <summary> /// /// </summary> public class CompositeBankAccountCommand : List<BankAccountCommand>, ICommand { /// <summary> /// /// </summary> public CompositeBankAccountCommand() { } /// <summary> /// /// </summary> /// <param name="collection"></param> public CompositeBankAccountCommand( [NotNull] IEnumerable<BankAccountCommand> collection) : base(collection) { } /// <summary> /// /// </summary> public virtual void Call() { Success = true; ForEach(cmd => { cmd.Call(); Success &= cmd.Success; }); } /// <summary> /// /// </summary> public virtual void Undo() { foreach (var cmd in ((IEnumerable<BankAccountCommand>)this).Reverse()) { cmd.Undo(); } } /// <summary> /// /// </summary> public bool Success { get; set; } } /// <summary> /// /// </summary> public class MoneyTransferCommand : CompositeBankAccountCommand { /// <summary> /// /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="amount"></param> public MoneyTransferCommand(BankAccount from, BankAccount to, int amount) { AddRange(new[] { new BankAccountCommand(from, BankAccountCommand.Action.Withdraw, amount), new BankAccountCommand(to, BankAccountCommand.Action.Deposit, amount), }); } /// <summary> /// /// </summary> public override void Call() { BankAccountCommand last = null; foreach (var cmd in this) { if (last == null || last.Success) { cmd.Call(); last = cmd; } else { cmd.Undo(); break; } } } }
调用:
//命令模式 Console.WriteLine("***命令模式 Command Pattern Demonstration***\n"); /*Client holds both the Invoker and Command Objects*/ RemoteControl invoker = new RemoteControl(); Game gameName = new Game("高尔夫游戏"); //Command to start the game GameStartCommand gameStartCommand = new GameStartCommand(gameName); //Command to stop the game GameStopCommand gameStopCommand = new GameStopCommand(gameName); Console.WriteLine("**开始游戏并立即执行撤销.**"); invoker.SetCommand(gameStartCommand); invoker.ExecuteCommand(); //Performing undo operation Console.WriteLine("\n现在撤消上一个命令"); invoker.UndoCommand(); Console.WriteLine("\n**重新开始游戏。然后停止它,撤销停止操作.**"); invoker.SetCommand(gameStartCommand); invoker.ExecuteCommand(); //Stop command to finish the game //执行停止操作 invoker.SetCommand(gameStopCommand); invoker.ExecuteCommand(); //Performing undo operation Console.WriteLine("\n现在撤消上一个命令."); invoker.UndoCommand(); Console.WriteLine(); // var b =new BankAccount(); var c=new FunctionalCommand(); c.Withdraw(b,2); Console.WriteLine(); // // composite var ba = new GevoinDuCommandPattern.BankAccount(); var cmdDeposit = new GevoinDuCommandPattern.BankAccountCommand(ba, GevoinDuCommandPattern.BankAccountCommand.Action.Deposit, 100); var cmdWithdraw = new GevoinDuCommandPattern.BankAccountCommand(ba, GevoinDuCommandPattern.BankAccountCommand.Action.Withdraw, 1000); var composite = new GevoinDuCommandPattern.CompositeBankAccountCommand(new[]{ cmdDeposit, cmdWithdraw }); composite.Call(); Console.WriteLine(ba); composite.Undo(); Console.WriteLine(ba); // money transfer var from = new GevoinDuCommandPattern.BankAccount(); from.Deposit(100); var toGeovinDu = new GevoinDuCommandPattern.BankAccount(); var mtc = new GevoinDuCommandPattern.MoneyTransferCommand(from, toGeovinDu, 1000); mtc.Call(); Console.WriteLine(from); Console.WriteLine(toGeovinDu); mtc.Undo(); Console.WriteLine(from); Console.WriteLine(toGeovinDu);
输出:
***命令模式 Command Pattern Demonstration*** **开始游戏并立即执行撤销.** 高尔夫游戏 开始. 比分随时在变化. 现在撤消上一个命令 取消起动命令. ---游戏: 高尔夫游戏 完成结束.--- **重新开始游戏。然后停止它,撤销停止操作.** 高尔夫游戏 开始. 比分随时在变化. 完成游戏. ---游戏: 高尔夫游戏 完成结束.--- 现在撤消上一个命令. 取消停止命令. 高尔夫游戏 开始. 比分随时在变化. 0:100 2:2 Deposited $100, balance is now 100 balance: 100 Withdrew $100, balance is now 0 balance: 0 Deposited $100, balance is now 100 balance: 100 balance: 0 balance: 100 balance: 0 t
标签:core,Console,Pattern,void,amount,Command,WriteLine,balance,public From: https://www.cnblogs.com/geovindu/p/16773897.html