Hello, I'm certainly not an expert programmer but I've been trying to learn about various design patterns.
My project uses the command pattern but I'm having trouble with some circular dependancies.
In essence here's the format:
I have a board that is loaded with a board state (such that board states can be interchangeable later).
A board state can contain one or many commands. A command inherits from the iCommand interface and executes some custom code.
Calling execute on the board calls execute on the board state which in this example calls execute on the only command.
What I'm trying to achieve though, is have a command that is able to call public functions on the board.
My initial thought was to forward declare the board class and have the iCommand class hold a static variable which is a pointer to a board. That way any commands can inherit from iCommand and also use the pointer.
Here's as far as I've gotten but I can't make it work. I'm trying to call board.test() from inside a concrete command.
Any ideas where this is falling short?
P.s please excuse that this is in C++ and not arduino with setup() loop() I've been testing without the arduino at this stage.
#include <iostream>
using namespace std;
class Board;
class iCommand{
public:
static Board* board;
virtual void execute(){}
iCommand(){}
};
class Command : public iCommand
{
public:
void execute(){iCommand::board->test();}
Command(){}
};
class BoardState{
public:
iCommand* command = new Command;
void execute(){command->execute();}
};
class Board{
public:
BoardState* boardState = new BoardState;
void execute(){boardState->execute();}
void test(){cout << "Success!";}
Board(){}
};
int main(int argc, char *argv[])
{
Board board;
iCommand::board = &board;
board.execute();
}
Error I'm getting here is
/storage/emulated/0/Download/newfile.cxx:17:32: error: member access into incomplete type 'Board'
void execute(){iCommand::board->test();}
^
/storage/emulated/0/Download/newfile.cxx:4:7: note: forward declaration of 'Board'
class Board;
^
1 error generated.
I guess to speak to the design pattern a little more, I have an invoker that is also a receiver.