How to implement State Design Pattern in C++

Posted by TheEyebal@reddit | learnprogramming | View on Reddit | 4 comments

I am learning state design pattern and I am struggling with implementing it. I read the Design Patterns: Elements of Reusable Object-Oriented Software and understood the concept

I am also reading this to understand state design patterns.

I've also watched a number of different youtube videos, drawn it out on a whiteboard, and scrolling on reddit, wikipedia, and stack overflow to understand it but so far I am lost

I have resorted to asking ChatGPT for help (which I hate) but also still confused

What I understand from this site is there is a context class that delgates behavior of the object to the states

I had wrote this thinking that this was a context class but according to ChatGPT it is not

#include <iostream>

using namespace std;

// a class holding an enum, not a true state pattern implementation.

enum controlSwitch { // List out the states
        ON = 1,
        OFF = 0
};

class Light { // Context class
        public:
        enum controlSwitch bulb; // create an enum variable

        Light(controlSwitch state){ // Constructor
                bulb = state; // enum variable = state parameter
        }
};

int main(){
        Light myLight(OFF); // create class variable

        cout << myLight.bulb << endl; // reads the value of the enum

        return 0;
}

Apparently I am suppose to have a context class move to the next state. So I would need a ON class and OFF class.

what is the pre requisite

I am at a lose, can someone help with this