C# Command Design Patter Class Question

CipherIS
CipherIS used Ask the Experts™
on
I am following the code in the below example.  For the most part it fits my needs.

http://www.dotnet-tricks.com/Tutorial/designpatterns/23JE110913-Command-Design-Pattern---C

All of my commands need to execute.  However two commands actually needs to return different values.  Is there a way to modify the pattern so I can return values for these two commands but leave the other commands executing as is?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Kyle AbrahamsSenior .Net Developer

Commented:
If I understand you correctly you may want to do an integer or an enum type of value . . . then you can set that in the execute and return whatever value you needed.

If you showed your code and what you were trying to do it would be helpful.
Daniel Van Der WerkenIndependent Consultant

Commented:
There are probably a couple of ways to do this -- if I understand what you want to do correctly.

Option 1: Create an object, you populate this object when the command executes, and then populate part of the object that's appropriate to the information you want returned and return the whole object.

Option 2: Return a Tuple<type1, type2> where you are, again, populating the type appropriately.

On the receiving end, you'll need to know what you're looking for. So, example:

public class MyInfoObject
{
     public  int MyNumberOfThingiesDone;
     public string MyReallyCoolInfo;
}

Open in new window

then
public interface ICommand
{
      MyInfoClass Execute();
}

Open in new window

Something like:
public class FlipDownCommand : ICommand
{
 private Light _light;
 
 public FlipDownCommand(Light light)
 {
 _light = light;
 }
 
 public MyInfoClass Execute()
 {
     MyInfoClass infoClass = new MyInfoClass();
     infoClass.MyNumberOfThingiesDone = 101;
     infoClass.MyReallyCoolInfo = string.Empty;
     _light.TurnOff();
     return infoClass;
 }
}

Open in new window

public class FlipUpCommand : ICommand
{
 private Light _light;
 
 public FlipUpCommand(Light light)
 {
 _light = light;
 }
 
 public MyInfoClass Execute()
 {
     MyInfoClass infoClass = new MyInfoClass();
     infoClass.MyNumberOfThingiesDone = int.MinValue;
     infoClass.MyReallyCoolInfo = "Kittens are cute."
     _light.TurnOn();
     return infoClass;
 }
}

Open in new window


And also:
public class Switch
{
 private List<ICommand> _commands = new List<ICommand>();
 
 public MyInfoClass StoreAndExecute(ICommand command)
 {
      _commands.Add(command);
      return command.Execute();
 }
}

Open in new window

then in use:
 if (cmd == "ON")
 {
   string infoINeed = s.StoreAndExecute(switchUp);
 }
 else if (cmd == "OFF")
 {
   int InfoNumbers = s.StoreAndExecute(switchDown);
 }
 else
 {
 Console.WriteLine("Command \"ON\" or \"OFF\" is required.");
 }

Open in new window


The Tuple implementation would be similar.

Does this help?
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
While Tuple would work functionally, semantically you would be doing a disservice to other developers reading your code. With a Tuple, you get properties such as Item1, Item2, Item3, etc. There's no meaning behind those names. The meaning is in the value itself. I would lean more towards the custom class, or possibly a generic implementation of your command classes.
If you want to keep your interface consistent, modify the return type of the Execute method from void to a generic return type - may be you can create a new type.

I have modified my previous example (http://www.experts-exchange.com/questions/28926412/C-Write-a-class-checking-for-commands.html) to
(1) Change the return type of the ICommand.Execute method to return a generic type "CommandExecutionResult".
(2) Create a new type called "CommandExecutionResult", which just wraps around a Point.
(3) Add a static property called "Empty" in the new "CommandExecutionResult" class, which returns a CommandExecutionResult with default/empty values (semantically here I am assuming that an empty/default point means (0,0) - which doesn't make much sense in reality).
(4) All concrete implementations of commands except the newly introduced "GetDiagonallyOppositPointCommand" returns a CommandExecutionResult.Empty from its Execute method after "performing the action".
(5) The newly implemented "GetDiagonallyOppositPointCommand" returns a CommandExecutionResult which contains a Point which is diagonally opposite to the "receiver" point.
(6) Invoker class now has a property called Result of type "CommandExecutionResult".

Check if this meets your needs:


using System;

namespace CommandsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p = new Point
            {
                X = 2,
                Y = -5
            };
                        
            Invoker invoker = new Invoker(p);

            // Execute "Up"
            ICommand command = new UpCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Left"
            command = new LeftCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Down"
            command = new DownCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Right"
            command = new RightCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Get the diagonally opposite point
            command = new GetDiagonallyOppositPointCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", invoker.Result.Value.X, invoker.Result.Value.Y);

            Console.ReadKey();
        }
    }

    class Point
    {
        public int X { get; set; }
        public int Y { get; set; }


    }

    interface ICommand
    {
        CommandExecutionResult Execute(Point p);
    }

    class UpCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.Y++;
            return CommandExecutionResult.Empty;
        }
    }

    class DownCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.Y--;
            return CommandExecutionResult.Empty;
        }
    }

    class LeftCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.X--;
            return CommandExecutionResult.Empty;
        }
    }

    class RightCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.X++;
            return CommandExecutionResult.Empty;
        }
    }

    class GetDiagonallyOppositPointCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            return new CommandExecutionResult
            {
                Value = new Point
                {
                    X = -1 * p.X,
                    Y = -1 * p.Y
                }
            };
        }
    }

    class Invoker
    {
        private Point _point;
        private ICommand _command;
        public CommandExecutionResult Result { get; private set; }

        public Invoker(Point point)
        {
            _point = point;
        }

        public void SetCommand(ICommand command)
        {
            _command = command;
        }

        public void ExecuteCommand()
        {
            Result = _command.Execute(_point);
        }
    }

    class CommandExecutionResult
    {
        public static CommandExecutionResult Empty
        {
            get
            {
                return new CommandExecutionResult
                {
                    Value = new Point
                    {
                        X = 0, Y = 0
                    }
                };
            }
        }

        public Point Value { get; set; }
    }
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial