命令模式 回滚
作者:互联网
public class BankAccount { private int balance; private int overdraft = -500; /// <summary> /// 存款 /// </summary> /// <param name="amount"></param> public void Remittance(int amount) { if (amount < 0) throw new ArgumentException("汇款金额错误"); balance += amount; } /// <summary> /// 取款 /// </summary> /// <param name="amount"></param> public void Withdrawal(int amount) { if (amount < 0) throw new ArgumentException("汇款金额错误"); if (balance - amount < overdraft) { throw new ArgumentException("余额不足!"); } balance -= amount; } public override string ToString() { return $"balance:{balance}"; } } public interface ICommand { void Call(); void Undo(); } public class BankCommand:ICommand { public enum OpType { 存款, 取款 } private BankAccount bankAccount; private OpType opType; private int amount; public BankCommand(BankAccount bankAccount, OpType opType, int amount) { this.bankAccount = bankAccount; this.opType = opType; this.amount = amount; } public void Call() { switch (opType) { case OpType.存款: bankAccount.Remittance(amount); Console.WriteLine($"{DateTime.Now}:存款 {amount} 余额:{bankAccount}"); break; case OpType.取款: bankAccount.Withdrawal(amount); Console.WriteLine($"{DateTime.Now}:取款 {amount} 余额:{bankAccount}"); break; default: break; } } public void Undo() { switch (opType) { case OpType.存款: bankAccount.Withdrawal(amount); Console.WriteLine($"{DateTime.Now}:存款取消 {amount} 余额:{bankAccount}"); break; case OpType.取款: bankAccount.Remittance(amount); Console.WriteLine($"{DateTime.Now}:取款取消 {amount} 余额:{bankAccount}"); break; default: break; } } } class Program { static void Main(string[] args) { BankAccount bank = new BankAccount(); var commands = new List<BankCommand>() { new BankCommand(bank, BankCommand.OpType.存款,600), new BankCommand(bank, BankCommand.OpType.取款,300), new BankCommand(bank, BankCommand.OpType.存款,500), }; commands.ForEach(c => c.Call()); Console.WriteLine(bank); foreach (var item in Enumerable.Reverse(commands)) { item.Undo(); } Console.WriteLine(bank); } }
标签:bankAccount,回滚,OpType,模式,命令,amount,BankCommand,new,public 来源: https://www.cnblogs.com/Zingu/p/16312675.html