Is it possible to implement the state design pattern in C++ without dynamic polymorphism?

216 views Asked by At

Let's say I have following C++ code

class ControlAlgorithm {

public:
    virtual void update() = 0;
    virtual void enable() = 0;
    virtual void disable() = 0;
};

class Algorithm_A : public ControlAlgorithm {

public:
    void update();
    void enable();
    void disable();
};

class Algorithm_B : public ControlAlgorithm {

public:
    void update();
    void enable();
    void disable();
};

Algorithm_A algorithm_A;
Algorithm_B algorithm_B;
ControlAlgorithm *algorithm;

Lets's say I would like to switch between the algorithm_A and algorithm_B during run-time based on some external events (basically I am going to implement the state design pattern). So the algorithm pointer points either to the algorithm_A or algorithm_B object. My question is whether there is any method how to achieve the ability to dynamic switch between the algorithms during run-time without the virtual methods in the common interface e.g. the curiously recurring template pattern?

1

There are 1 answers

2
jwezorek On BEST ANSWER

You could use composition over inheritance. Something like below, for example.

#include <iostream>
#include <functional>

struct control_algorithm {
    const std::function<void()> update;
    const std::function<void()> enable;
    const std::function<void()> edit;
};

control_algorithm make_algorithm_A() {
    return {
        []() { std::cout << "update A\n"; },
        []() { std::cout << "enable A\n"; },
        []() { std::cout << "edit A\n"; },
    };
}

control_algorithm make_algorithm_B() {
    return {
        []() { std::cout << "update B\n"; },
        []() { std::cout << "enable B\n"; },
        []() { std::cout << "edit B\n"; },
    };
}

int main()
{
    auto algorithm_A = make_algorithm_A();
    auto algorithm_B = make_algorithm_B();
    auto control = algorithm_A;
    //auto control = algorithm_B;
}