Let's say I would like to maintain variables, such as:
1 2 3
bool usbConnected; //Whether the USB connection has been established
int programState; //Which state the program is in (i.e. busy, waiting, menu, etc.)
int progress; //Some variable to keep track of program progress
etc.
How would I keep track of this? I've read up and have been cautioned against using the Singleton pattern and static classes. Would there be something else appropriate for this?
What it gives you is an "interface". It facilitates component interchange. Say at some point you want to change the behavior of your GUI's back-end (which was previously DerivedInstance).
class Instance
{
public:
virtualbool usbConnected() const = 0;
virtual ProgramState getProgramState() const = 0;
virtualint getProgress() const = 0;
};
class USBConnection;
class DerivedInstance : public Instance
{
USBConnection connection;
virtualbool usbConnected() const
{
return connection.isConnected();
}
virtual ProgramState getProgramState() const {/* ... */ }
virtualint getProgress() const {/* ... */ }
}
class AnotherDerivedInstance : public Instance
{
std::list<USBConnection> connections;
virtualbool usbConnected() const
{
for(std::list<USBConnection>::const_iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if(iter->isConnected())
{
returntrue;
}
}
returnfalse;
}
virtual ProgramState getProgramState() const {/* ... */ }
virtualint getProgress() const {/* ... */ }
}
class AwesomeGUI;
int main()
{
AwesomeGUI gui1(std::shared_ptr<Instance>(new DerivedInstance()));
AwesomeGUI gui2(std::shared_ptr<Instance>(new AnotherDerivedInstance()));
// The same AwesomeGUI can be used for both derived types without any code duplication.
}
It's a pattern that I use very frequently in my projects. Hope it helps.
P.S. The same effect can be achieved through templates with a negligible performance boost, but I usually prefer to use an inheritance setup. It's all a matter of personal style.