1

A lot of times we need a demo mode in certain projects which usually involves hardware with the purpose that the software can run/simulate without the hardware actually connected. The functions in demo mode simulate the hardware somewhat but don't obviously operate on it.

My question is, is the proxy design pattern (or any other for that matter) a good fit to create demo modes in software?

Consider the example below which is simplified to be short.

class Arm
{
public:
    int _x = 0;
    int _y = 0;

    virtual void move(int x, int y) = 0;
};

class RobotArm : public Arm
{
    virtual void move(int x, int y)
    {
        /* assum we have actual hardware coommands here which updates variables */
        //_x = x;
        //_y = y;

        std::cout << "hardware is not connected, can't move" << std::endl;
    }
};

class RobotArmDemo : public Arm
{
    virtual void move(int x, int y)
    {
        /* no hardware commands here, just update variables */
        _x = x;
        _y = y;

        std::cout << "Demo Arm moved to " << _x << "," << _y << std::endl;
    }
};

class Robot
{
public:
    Arm *leftArm;
    Arm *rightArm;
};

int main()
{
    Arm * leftArm = new RobotArmDemo; // creating an arm in demo mode!
    Arm * rightArm = new RobotArm; // this arm is the real one

    Robot * robot = new Robot;

    robot->leftArm = leftArm;
    robot->rightArm = rightArm;

    // perform action
    robot->leftArm->move(3, 3); // this is on demo mode
    robot->rightArm->move(1, 2); // this is real mode

    return 0;
}

In the code above, I created one demo arm and one real arm for the robot just to show how each will work. Obviously in real demo mode, all derived objects will have the demo implementation. Is this a good way to implement demo modes in software?

Can this be applied to real large/medium size application? I tend to like this approach because exactly same functions are called in both real and demo applications which makes life easier and understand the flow. Alternatively a seperate 'demo' path can become almost a seperate application/module which grows apart and loses close resemeblence with real application.

zar
  • 11,361
  • 14
  • 96
  • 178
  • Your approach is fine, but this is not a proxy pattern, there is no proxy. – Alexey Guseynov Nov 16 '16 at 21:16
  • maybe a better term would be dependency injection, see here: http://stackoverflow.com/questions/5585436/using-interface-in-c-for-dependency-injection – marcinj Nov 16 '16 at 21:25
  • @AlexeyGuseynov yes I figured it's not exactly proxy but has somewhat similar class design. – zar Nov 16 '16 at 22:32

1 Answers1

0

Yes this looks like a good approach.

What you can also consider beyond your design, is a abstract factory class creating the robot, which creates the correct objects (either demo or real classes). So the first 5 lines of the main function will end up in the factory class.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119