CSharp: Command Pattern in donet core 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | /// <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(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | /// <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()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | /// <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 ; } } } } |
调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | //命令模式 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); |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | ***命令模式 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 |
Development environment(开发环境), Integration environment(集成环境),Testing environment (测试环境), QA (quality assurance) ensures(QA验证) , Staging environment(模拟环境),Production environment(生产环境)
Cloud Architecture, Cloud Solutions, Product Development, Software Architecture, Software Development Life Cycle, Technical Consulting
DTAP (Development, Testing, Acceptance, and Production)
DEV — Development [Software developer] SIT — System Integration Test [Software developer and QA engineer] UAT — User Acceptance Test [Client] PROD — Production [Public user]
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
分类:
CSharp code
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!