Robotic Interface
The following is one possible solution to this challenge.
Robot robot = new Robot();
for(int index = 0; index < robot.Commands.Length; index++)
{
string? input = Console.ReadLine();
robot.Commands[index] = input switch
{
"on" => new OnCommand(),
"off" => new OffCommand(),
"north" => new NorthCommand(),
"south" => new SouthCommand(),
"east" => new EastCommand(),
"west" => new WestCommand(),
};
}
Console.WriteLine();
robot.Run();
public class OffCommand : IRobotCommand
{
public void Run(Robot robot) => robot.IsPowered = false;
}
public class OnCommand : IRobotCommand
{
public void Run(Robot robot) => robot.IsPowered = true;
}
public class WestCommand : IRobotCommand
{
public void Run(Robot robot) { if (robot.IsPowered) robot.X--; }
}
public class EastCommand : IRobotCommand
{
public void Run(Robot robot) { if (robot.IsPowered) robot.X++; }
}
public class SouthCommand : IRobotCommand
{
public void Run(Robot robot) { if (robot.IsPowered) robot.Y--; }
}
public class NorthCommand : IRobotCommand
{
public void Run(Robot robot) { if (robot.IsPowered) robot.Y++; }
}
public interface IRobotCommand
{
void Run(Robot robot);
}
public class Robot
{
public int X { get; set; }
public int Y { get; set; }
public bool IsPowered { get; set; }
public IRobotCommand?[] Commands { get; } = new IRobotCommand?[3];
public void Run()
{
foreach (IRobotCommand? command in Commands)
{
command?.Run(this);
Console.WriteLine($"[{X} {Y} {IsPowered}]");
}
}
}
// Answer this question: Do you feel this is an improvement over using an abstract base class? Why or why not?
//
// In this situation, I think this is better. For starters, there's less code to do the same thing. No need
// to have those abstracts and overrides everywhere. But at a more substantial level, inheritance is a pretty
// strong relationship, and these commands do not really need to have that strong of a relationship to each
// other. The only thing that really binds them together is that they do the same type of thing. So I think
// it is better for that reason.