mardi 5 juin 2018

Alternative to Visitor Pattern

A known problem with Visitor Pattern is that is doesn't scale well with a rich hierarchy of classes ( Even if you don't add classes often).

When you combine visitor pattern with command pattern hell gates opens. Your visitor interface now has to support all the types of your hierarchy, which might not be desired.

For example, you might want to divide your commands into categories:

class CarCommands
{
protected:
        enum TypeOfCommands : uint8_t
        {
                RadioCommands,
                EngineCommands,
                WindowsCommands,

                MaxCarCommands
        };

        uint8_t cmd_type;
};

From there, you write your supreclasses:

class RadioCmd : CarCommands
{
public:
    RadioCmd() : CarCommands(RadioCommands)
    {}

    // Other radio-specific methods
    ...
    // Other radio-specific data members
    ...
protected:
    enum TypeOfRadioCmd : uint8_t
    {
        Radio_ON,
        Radio_OFF,

        MaxRadioType
    };

    uint8_t radio_type;
};

class EngineCmd : CarCommands
{
pubilc:
    EngineCmd() : CarCommands(EngineCommands)
    {}
protected:
    enum TypeOfEngineCmd : uint8_t
    {
        Engine_Start,
        Engine_Accelerate,
        Engine_Stop,

        MaxEngineType
    };

    uint8_t engine_type;
};

It feels natural to have a handler for each category. If I would want to process Engine-related commands, my EngineCommandHandler should not know about other types of CarCommands. Thus, if I decide to add another engine command, I would only have to modify the EngineCommandHandler in order to support it. At the same time, a CarCommandHandler should be able to process correctly a AccelerateEngine command.

Is there an alternative for visitor pattern that scales with a large class hierarchy? Given the problem, is there another design-pattern that applies better than visitor pattern ?

Aucun commentaire:

Enregistrer un commentaire