`
chenying998179
  • 浏览: 25805 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

The Command Pattern Example in C#

 
阅读更多

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.

Command Pattern Class Diagram

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();
        }
    }
}

Vending Machine Console

分享到:
评论

相关推荐

    命令模式command pattern

    命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,使得你可以使用不同的请求、队列请求,或者支持可撤销的操作。在Java中实现命令模式,我们可以利用面向对象编程的特性来构建系统,使得...

    Design Pattern In c#

    《Design Pattern In C#》是一本深入探讨设计模式的书籍,专为使用C#编程语言的开发者准备。设计模式是软件工程中经过实践验证的、解决常见问题的有效方法,是经验丰富的开发者的智慧结晶。这本书以英文撰写,以其...

    业务层框架 —— Command Pattern指南.mht

    业务层框架 —— Command Pattern指南.mht业务层框架 —— Command Pattern指南.mht

    Design Pattern in C#

    3. 行为型模式:包括策略模式(Strategy)、模板方法模式(Template Method)、观察者模式(Observer)、命令模式(Command)、责任链模式(Chain of Responsibility)、迭代器模式(Iterator)、访问者模式...

    Data Science at the Command Line

    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-...

    C#中Command对象的用法

    ### C#中Command对象的深度解析与应用实例 在C#编程中,处理数据库操作时,`Command`对象扮演着核心角色。它充当了应用程序与数据库之间的桥梁,负责执行SQL语句、存储过程或直接处理特定表格。本文将深入探讨`...

    Extreme Programming Adventures in C#

    《Extreme Programming Adventures in C#》一书由Ron Jeffries撰写,是C#设计模式领域的一部佳作,对于深入理解极限编程(Extreme Programming,简称XP)具有重要价值。该书通过一系列的故事和实践,展示了如何在...

    c++-设计模式之命令模式(Command Pattern)

    命令模式(Command Pattern)是一种行为型设计模式,它将请求封装为对象,从而使您可以使用不同的请求、队列请求或日志请求,并支持可撤销操作。命令模式通常用于实现操作的解耦,使得发送者和接收者之间不直接关联...

    DoFactory Design Pattern Framework 3.5 C#

    总的来说,DoFactory Design Pattern Framework 3.5 C#是C#开发者学习和应用设计模式的强大工具,它将设计模式的理论知识与实际开发紧密结合,有助于提升开发者的专业技能和软件设计能力。无论是初学者还是经验丰富...

    CommandPattern)管理智能家电最终代码共4页.pdf.zip

    命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,使得你可以用不同的请求参数化其他对象。此外,命令模式支持可撤销的操作。在这个"CommandPattern)管理智能家电最终代码共4页.pdf.zip...

    CommandPattern)管理智能家电最终代码共4页

    **命令模式(Command Pattern)详解** 命令模式是一种行为设计模式,它将请求封装为一个对象,使得你可以使用不同的请求、队列或者日志请求,也可以支持可撤销的操作。在这个场景中,我们关注的是如何利用命令模式...

    C#命令行解析CommandLine

    本文将深入探讨如何在C#中解析命令行参数,以实现`CommandLine`的高效利用。 命令行参数是在程序启动时通过操作系统传递给程序的一系列字符串。在C#中,这些参数可以通过`Main`方法的`args`参数访问。`Main`方法是...

    Working with Linux Quick Hacks for the Command Line epub

    Working with Linux Quick Hacks for the Command Line 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    命令模式(Command Pattern).rar

    用最简单的例子理解命令模式(Command Pattern) 命令模式的需求源自想通过一个指令(比如这里IControl的Execute方法)来控制多个类的多个方法,包含了几个要素: 1、命令:让类的各种方法抽象成类实现一个接口 2、...

    C#命令模式(Command Pattern)实例教程

    调用者通过`AddOnCommand`、`AddOffCommand`和`AddSwitchCommand`方法来添加相应的命令对象,这样就可以在后续调用`ExecuteCommand`时执行对应的命令。 这样的设计使得遥控器(调用者)无需知道每个操作的具体实现...

    ANSYS Mechanical APDL Command Reference.pdf

    A command mentioned in the various analysis guides implies a link to the detailed command description given in this reference. For ordering purposes, the alphabetical ordering of commands that begin ...

Global site tag (gtag.js) - Google Analytics