The Command Pattern makes a execution request into an object. This makes it possible to store, search and transport requests and let clients call them via a common interface. This pattern is often used to implement undo or macro operations. A command has a execution method without any parameters to invoke the associated operation. The client can however provide context by setting properties.
In this example we build a simple vending machine console application, with cold beverages, hot coffee and peanuts (yes that’s very possible in my world). We implement the ICommand interface for each command to get the good stuff from the machine.
We also cheat a little by implementing the ICommandFactory Create() method on each command. This maybe violates the single responsibility principle, but gives us the convenience to write only one class if we need to add another command.
A single implementation of a command, in this case the GetBeverage command, will look something like this.
using System;
using System.Diagnostics;
namespace CommandPatternConsole
{
public class GetBeverageCommand : ICommand, ICommandFactory
{
public bool Sparkling { get; set; }
#region ICommand Members
public string Name
{
get { return "GetBeverage"; }
}
public string Description
{
get { return "GetBeverage [sparkling]"; }
}
public void Execute()
{
// Get some coffee
Console.WriteLine(
"Here's your drink {0} ",
Sparkling ? "and it sparkles." : string.Empty);
// Log the command
Debug.WriteLine("{0}: {1} called",
DateTime.Now,
ToString());
}
#endregion
#region ICommandFactory Members
public ICommand Create(string[] args)
{
string arg1 = string.Empty;
if (args.Length == 2)
{
arg1 = args[1];
}
return new GetBeverageCommand
{
Sparkling = arg1 == "sparkling",
};
}
#endregion
}
}
A CommandParser tries to interpret the command line arguments. If it finds the right command it tries to create one with properties set by calling the Create() method with the arguments.
using System.Collections.Generic;
using System.Linq;
namespace CommandPatternConsole
{
public class CommandParser
{
private readonly IEnumerable<ICommand> _commands;
public CommandParser(IEnumerable<ICommand> commands)
{
_commands = commands;
}
internal ICommand Parse(string[] args)
{
string commandName = args[0];
ICommand command = Find(commandName);
return ((ICommandFactory) command).Create(args);
}
private ICommand Find(string commandName)
{
return _commands
.FirstOrDefault(c => c.Name == commandName);
}
}
}
If all according to plan the command gets executed. If the parser can’t resolve the command, an exception is thrown and the application prints a list of possible commands to the console.
using System;
using System.Collections.Generic;
namespace CommandPatternConsole
{
internal class Program
{
private static void Main(string[] args)
{
IEnumerable<ICommand> commands = GetCommands();
try
{
var parser = new CommandParser(commands);
ICommand command = parser.Parse(args);
command.Execute();
}
catch (Exception)
{
Console.WriteLine("Invalid command {0}", args);
PrintInstructions(commands);
}
}
private static IEnumerable<ICommand> GetCommands()
{
return new List<ICommand>
{
new GetBeverageCommand(),
new GetCoffeeCommand(),
new GetPeanutsCommand(),
};
}
private static void PrintInstructions(IEnumerable<ICommand> commands)
{
Console.WriteLine();
Console.WriteLine("*** VENDING MACHINE commands ***");
Console.WriteLine();
foreach (ICommand command in commands)
{
Console.WriteLine("- {0}", command.Description);
}
Console.WriteLine();
}
}
}
分享到:
相关推荐
用java实现命令模式。展现命令模式类与类之间的继承,依赖关系。
Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with ...
业务层框架 —— Command Pattern指南.mht业务层框架 —— Command Pattern指南.mht
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。
This hands-on guide demonstrates how the flexibility of the command line can help you become a more efficient and productive data scientist. You’ll learn how to combine small, yet powerful, command-...
CommandPattern)管理智能家电最终代码共4页.pdf.zip
主要介绍了C#命令模式(Command Pattern),以实例的形式讲述了命令模式通过一个指令来控制多个类的多个方法,需要的朋友可以参考下
CommandPattern)管理智能家电最终代码共4页.pdf.zip
All Linux users and administrators tend to like the flexibility and speed of Linux administration from the command line in byte–sized chunks, instead of fairly standard graphical user interfaces....
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
介绍了C#中Command对象的各种用法和详细解释
本书是The Linux Command Line 的中文版,帮助新手入门和老鸟进阶,可以中英文对照着读,效果更佳(小小搬运工,省的大家去找,不喜勿喷)
Introduction to the Command Line
Working with Linux Quick Hacks for the Command Line 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with ...
用最简单的例子理解命令模式(Command Pattern) 命令模式的需求源自想通过一个指令(比如这里IControl的Execute方法)来控制多个类的多个方法,包含了几个要素: 1、命令:让类的各种方法抽象成类实现一个接口 2、...
C#命令行解析,简单实用 CommandLine CommandArgs
Zed. A. Shaw编写的,上传者只是将它整理成文档
Head First 设计模式 (六) 命令模式(Command pattern) C++实现