Problem in designing software using strategy pattern - c++

I am currently implementing a small soft, I want this soft work on Mac OS and Window OS, so I want use GLFW for Mac environment and Window API for Windows environment (I know GLFW is cross platform but that's not the point..)
My problem is a design implementation problem:
I have created a windowManager class that keeps an instance of a Window class. This Window keeps an instance of an object that is a PatternWindow, where PatternWindow is an interface. I have an object PatternGLFW3_VULKAN that implements PatternWindow. This PatternGLFW3_VULKAN has a member GLFWwindow * _window, and PatternGLFW3_VULKAN initializes _window with glfwCreateWindow(...).
class Window : public Singleton<Window>
{
public:
somefunction(...)
initializePatternWindow(unique_ptr<PatternWindow>&& patternWindow)
unique_ptr<PatternWindow> getPatternWindow(){return _patternWindow;}
private:
unique_ptr<PatternWindow> _patternWindow;
}
class PatternWindow
{
public:
PatternWindow();
virtual ~PatternWindow();
virtual void initialize() = 0;
virtual void destroy () = 0;
};
class PatternGLFW3_VULKAN : public PatternWindow
{
public:
PatternGLFW3_VULKAN ();
~PatternGLFW3_VULKAN();
virtual void initialize();
virtual void destroy();
const GLFWwindow& getWindow() const {return *_window;}
private:
GLFWwindow * _window;
};
My question is about the getWindow() function in my PatternGLFW3_VULKAN class; how I can create a virtual getWindow() function in my PatternWindow class in order to get my GLFWwindow* window of the PatternGLFW3_VULKAN at run time. If I am on Mac OS environment, I can create a virtual function GLFWwindow& getWindow() in my PatternWindow, but if I run my software in a Window environment, the type GLFWwindow of the virtual function getWindow() of the patternWindow class won't be correct...
How can I do in order to have a virtual getWindow() in PatternWindow my that returns GLFWwindow or a instance the Windows API screen at run time ?
EDIT:
class PatternWindow
{
public:
PatternWindow();
virtual ~PatternWindow();
virtual void initialize() = 0;
virtual void destroy () = 0;
virtual /*UNKNOW TYPE AT THE COMPILATION*/ getWindow() = 0;
};
/*UNKNOW TYPE AT THE COMPILATION*/
is my problem I do not know how to deal with it, for getting a GLFWwindow* when i am in Mac OS and Windows instance for the windows API when I am compiling in the Windows environment..
In the main loop of my software in want something like that
int main(int argc, char** argv)
{
//initialisation of all my managers ans the data ect..
while(!WindowClosed(Window::getPatternWindow()->getWindow()))
{
//DO SOME STUFF
}
}

The pattern you are heading towards can be done, but you might regret it later. I would infer from your setup that you have two overloads of WindowClosed() – one whose parameter is a GLFWwindow, and one whose parameter is a WinAPI type. The former would use GLFW methods to detect if the window is closed, while the latter would use the Windows API. One problem is that one of organization: how many files contain GLFW-specific methods? Maybe you even have a file with both GLFW methods and Win API methods? That's not necessarily wrong, but it could be a pain in the long run. Another problem is that this approach diverges from the traditional object-oriented approach.
Still, let's not force you down one path through lack of knowledge. To make this approach work, you could use the preprocessor and a typedef. If compiling for Mac, you would use a line like typedef PatternGLFW3_VULKAN WindowType;. If compiling for Windows, you'd use a line defining WindowType to be the corresponding Windows type. Choosing between these lines would be accomplished via #ifdef WINDOWS (or whatever condition is most appropriate). Then getWindow() could be declared to return WindowType.
A better approach (which you realized in the comments) is to shift the functionality to the window objects. Instead of function(object), use object.function(). This requires more virtual functions in your interface class, but there is a benefit that you have fewer files that are OS-specific.
class PatternWindow
{
public:
PatternWindow();
virtual ~PatternWindow();
virtual void initialize() = 0;
virtual void destroy () = 0;
virtual bool closed () = 0; // <-- New pure virtual function
};
class PatternGLFW3_VULKAN : public PatternWindow
{
public:
PatternGLFW3_VULKAN ();
~PatternGLFW3_VULKAN();
virtual void initialize();
virtual void destroy();
virtual bool closed(); // <-- OS-specific code is no longer in an extra file
private:
GLFWwindow * _window;
};
Then in your main function, the call would be:
while(!Window::getPatternWindow()->closed())
There is a further step you might consider. (The question appropriately does not have enough details to determine if this is a viable option.) You might not need polymorphism for what you are trying to do. Suppose you were to use the following declaration.
class PatternWindow
{
#ifdef WINDOWS // Or whatever test is appropriate
typedef PatternGLFW3_VULKAN * WindowType;
#else
typedef /* Windows API type */ WindowType;
#endif
public:
PatternWindow();
~PatternWindow();
void initialize();
void destroy ();
bool closed ();
private:
WindowType _window;
};
This interface no longer supports polymorphism. Is that a bad thing? Do you need multiple classes derived from PatternWindow under a single operating system? Perhaps not. Here is a potential implementation file for this class.
#include "PatternWindow.h"
#ifdef WINDOWS // Or whatever test is appropriate
#include "PatternWinAPI.src" // <-- File with an implementation based on Win API
#else
#include "PatternGLFW.src" // <-- File with an implementation based on GLFW
#endif
If you don't like the .src extension, use something else. Just don't make those files look like something to be compiled on their own. Each file would have an implementation appropriate for the API it uses. For example, PatternGLFW.src might contain a function definition like the following.
void PatternWindow::initialize()
{
_window = glfwCreateWindow(...);
// Etc.
}
This eliminates the overhead of polymorphism and does not seem to introduce a coding burden. Also, you don't have to keep track of which files are needed for which operating systems (simpler build setup). The organization of PatternWindow.cpp is uncommon, though.

Related

Singleton pattern with gtk3 and gtkmm

I'm working on a gui app with cpp and gtkmm3.
In this app, some widgets require the singleton pattern to implement such as window (because i want just one window in all over the app)
this is my header file:
class MyWindow : public Gtk::ApplicationWindow {
public:
MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> builder);
~MyWindow();
MyWindow(MyWindow const&) = delete;
void operator=(MyWindow const&) = delete;
static MyWindow* getInstance();
private:
MyWindow();
};
and source file is :
MyWindow::MyWindow(){}
MyWindow::MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk::Builder> refBuilder)
: Gtk::ApplicationWindow(pWindow),
builder(refBuilder) {
}
MyWindow::~MyWindow() {}
MyWindow *MyWindow::getInstance() {
static MyWindow *window;
return window;
}
my question is:
Is there a more appropriate and reasonable pattern instead singleton pattern ?
Is using this pattern suitable for the interface widgets and gui app ?
The major problem with the Singleton design pattern is that it gives you:
a single instance AND
global access.
The single instance aspect of the singleton is what people usually are looking for (like in your case), but not global access.
The usual "alternative" to this is to declare a MyWindow instance and then inject it to anyone who needs it. This is known as dependency injection. So you have something like:
void DoSomeThingOnWindow(MyWindow& p_window)
{
p_window.DoSomething();
}
// At the beginning:
MyWindow window;
// Everywhere else:
DoSomeThingWithTheWindow(window);
instead of:
void DoSomeThingOnWindow()
{
// Global access:
MyWindow* window = MyWindow::getInstance();
window->DoSomething();
}
// Everywhere:
DoSomeThingWithTheWindow();
The "bad" side of dependency injection over a singleton is that it will not enforce the single instance. However, if you use it everywhere and carefully, you can pass a single instance all around and not have global access, which will have so much more benefits.

Does C++ compiler optimize virtual member calls?

I'm thinking of creating a big new C++ project. The start is easy - just a simple window, maybe SDL2, maybe SFML, maybe even WIN32. Well, what should I take? Wouldn't it be much nicer to use any window I want to? Without changing much code so that other classes are independent of this window?
Said, done! Using a simple window interface, every class knows of something like a window and I'm able to choose between different types. The only requirement is having IWindow as a base class.
class IWindow {
public:
IWindow(std::string title, int posX, int posY, int width, int height);
IWindow getHandle();
void loop();
bool toggleFullscreen();
bool toggleFullscreen(bool fullscreen);
int getWidth();
int getHeight();
int getPosX();
int getPosY();
//And so on ...
};
But now, since I have to use virtual methods, every time my virtual function loop will be called by the game loop. And virtual functions are slower. About 10%, I've read.
Isn't the compiler able to see what my window will be? Of which type it'll be from? Couldn't it see "Jeah, this programmer guy creates an SDL window in this application, so just use it's methods everywhere."? I mean, I'm defining my window during the main loop and it'll never change. It's nothing dynamical. It's predictable.
So is the compiler able to optimize my predictable virtual function calls? These which will be evaluated every game loop cycle? Like in the following passage?
int main(int argc, char* argv[]) {
//Creates a window derived from IWindow
SDL::Window myWindow("Title", 0, 0, 300, 100);
//Storing it as IWindow in a wrapper class
Game myGame(&myWindow);
//Game loop
//myGame.run() calls the window's loop
while (myGame.run()) {
//... doing game stuff
}
}
With a Game class like this:
class Game {
protected:
IWindow* window;
public:
bool run() {
//Calls the window's virtual loop method.
//Will it be optimized? Any way to do so?
this->window->loop();
}
};
It would be nice to hear of your ideas and experiences.
Darth Moon
Does C++ compiler optimize virtual member calls?
Yes, a compiler might be able to de-virtualize virtual function calls if it can determine the concrete type at compile time.
No, a C++ compiler will not be able to de-virtualize all virtual function calls.
And virtual functions are slower. About 10%
Assuming the 10% difference is correct, consider that function call overhead is probably somewhere in magnitude of a few nano seconds. 10% of a few nano seconds is not a lot. You can fit many, many nano seconds in a single iteration of a soft real time simulation like a game.
Isn't the compiler able to see what my window will be?
So is the compiler able to optimize my predictable virtual function calls?
Maybe.
Firstly, call to run must be expanded inline in the context where the pointer is assigned. Otherwise it cannot make any assumptions about the pointed object. In order to be expanded inline, it must be defined in the same translation unit as where the function is called from (except, LTO may be able to lift this requirement).
Furthermore, the compiler must be able to prove that window is not modified at any point during the execution to point another object. This proof may be impossible depending on what your loop looks like, but there is a simple way to make it easy: declare the pointer const.
As for whether your compiler does optimize it... I don't know. But your compiler does, so I suggest directing your question to your compiler (i.e. ask it to compile your program and see what it does).
Let's sum up our comments.
Virtual calls are costly, but if the processor can detect a pattern, their calling cost gets decreased thanks to the predictors inside modern processors.
Now, let's check your code:
int main(int argc, char* argv[]) {
//Creates a window derived from IWindow
SDL::Window myWindow("Title", 0, 0, 300, 100);
//Storing it as IWindow in a wrapper class
Game myGame(&myWindow);
//Game loop
//myGame.run() calls the window's loop
while (myGame.run()) {
//... doing game stuff
}
}
Let's assume Game has a virtual run. In this instance, the compiler knows that myGame is of type Game and can directly put the call to your run function instead of going through the virtual table.
Now you have this in another file:
class Game {
protected:
IWindow* window;
public:
bool run() {
//Calls the window's virtual loop method.
//Will it be optimized? Any way to do so?
this->window->loop();
}
};
Unfortunately, in this case, there is nothing that the compiler can know by just looking at this file, and as such the call to SDL::Window will go through the virtual run coming from IWindow.
Now with lto (link time optimization), the compiler might be able to figure it out and de-virtualize the code, but it will probably not as the number of optimization options will grow with the number of files as well as the number of combinations.

Handling events raised from a lower level object

I'm writing a C++ programm using GTK+3.0. Anyway, I think this question may apply to any framework that uses events / signals.
I have a container class, say containerClass and a child class, say childClass. A childClass object child is contained inside a containerClass object container.
The child object is written to modify properties of something. To this aim, it has GtkEntry, GtkButton and so on. When I click the "save button", an event is raised.
This event must be handled by the container object, because the container is interfaced with a database in someway.
Hereafter, you find the solution I'm using to do the job:
// Child class
class childClass {
void setClickHandler_External(void (*extFun)(string property), void *);
void (*clickHandler_External)(string, void *);
void *clickHandler_External_Data;
static void buttonClicked(GtkWidget *widget, void *data);
}
void childClass::setClickHandler_External(void (*extFun)(string), void *data) {
// Set the external event handler
clickHandler_External = extFun;
clickHandler_External_Data = data;
}
void childClass::buttonClicked(GtkWidget *widget, void *data) {
childClass *m = (childClass *)data;
// Call the external event handler
m->clickHandler_External(property, m->clickHandler_External_Data);
}
// Container Class
class containerClass {
childClass child;
static void clickHandler(string property, void *data);
}
containerClass::containerClass() {
// Set the event handler
child.setClickHandler_External((void(*)(string))&(this->clickHandler), (void *)this);
}
void containerClass::clickHandler(string property, void *data) {
// Event handler in the upper class
containerClass *m = (containerClass *)data;
//FINALLY, DO THE JOB WITH PROPERTY!!!
}
This works well and does the job. Anyway, I was wondering if there is a smarter and cleaner way to achieve the same aim, maybe without using pointers to static functions, or by defining some kind of pattern to be reused everytime I need to have the same mechanism.
Thanks in advance
Gtkmm uses the sigc++ library to take care of all of this for you. There is no need to write it yourself.
Documentation links:
Signals overview
Appendix with detailed information
So, in this case, I would use something like
button.signal_clicked().connect(sigc::mem_fun(container, &containerClass::clickHandler));
while making sure that containerClass::clickHander has the appropriate number of arguments.
My first suggestion would be to use use templates to improve the type safety of what you are doing:
template< class ParamType >
void childClass::setClickHandler_External(void (*extFun)(string, ParamType *),
ParamType *data)
{
// Set the external event handler
clickHandler_External = (void ()(string,void*))extFun;
clickHandler_External_Data = (void*)data;
}
Then you can simplify the containerClass implementation as such:
// Container Class
class containerClass {
childClass child;
static void clickHandler(string property, containerClass *data);
}
containerClass::containerClass() {
// Set the event handler
child.setClickHandler_External(&containerClass::clickHandler, this);
}
void containerClass::clickHandler(string property, containerClass *data) {
//FINALLY, DO THE JOB WITH PROPERTY!!!
}
While it's great that this cleans up the implementation, removing the explicit casting from all the container implementors, that's not really the point. The point is to prevent you from passing wrong pointers into setClickHandler_External, causing crashes on the back end when events get dispatched.
My next step would take us further from your implementation, but would require more details about what you are actually doing. Depending on your needs that would be looking into:
Inheritance: should containerClass derive from childClass? That would provide access to a virtual function table that we could override.
Functors: look at boost::function and boost::bind to implement functors, eliminating the intermediate static function call.
Lambda Functions: bleeding edge (C++11 or later), but may be a good fit for this kind of forwarding function.

Safety using entity from different part of program

I have several modules in my program (e.g. Database, Scheduler) which uses same entity - some game server.
Main goal is that each module uses game server API with limited functionality (functionality which need for interaction between separate module and game server only) and other functions must be hide.
I have created such functionality. But I don't now, maybe it's wrong realization or maybe somebody guess better method.
Class which placed below contain some operations which can be access only from others modules via classes wrappers.
#ifndef _GAMESERVER_
#define _GAMESERVER_
#include <vector>
class GameServer
{
static GameServer instance;
std::vector<int> game_actions;
GameServer(){}
~GameServer(){}
GameServer(const GameServer&){}
protected:
void addGameAction(int action) // Some functionality, which can be accessible only from others modules via classes wrapers
{
game_actions.push_back(action);
}
public:
static GameServer *getInstance()
{
return &instance;
}
bool start()
{
return true;
}
void stop()
{
}
};
#endif
Below placed class 'wrapper' for class GameServer which has been realising API for interaction with module Database.
#ifndef _DBGAMESERVER_
#define _DBGAMESERVER_
/* Database module will use this API for interacting with game server */
class GameServer;
class DBGameServer : protected GameServer
{
DBGameServer();
public:
static DBGameServer *getInstance()
{
return static_cast<DBGameServer *>(GameServer::getInstance());
}
void addGameAction(int action)
{
GameServer::addGameAction(action);
}
};
#endif
Thanks!
You are creating your singleton instance at first call to getIntance. It may be unsafe in a multithreaded application : race conditions could lead to multiple instances being actually intialized and used.
IMHO you would better use static initialization :
Declaration :
...
class GameServer {
static GameServer& instance;
// private constructor, copie constructor and destructor
...
public:
static GameServer * getInstance() { return &instance; }
...
}
Implementation :
...
GameServer & GameServer::instance = GameServer();
...
That way you are sure that the object is constructed only once during program start (before first instruction), and destructor is called at program end (after last instruction). Of course if constructor throws an exception the program will stop abruptly before it is given any chance to display anything : the eventual error messages should be displayed inside constructor.

Passing Data Between abstract classes

I'm looking for opinions on the best OO way to accomplish what I am about to describe. I'm writing what is going to become an event system for games and the like and I want it to be as extensible as possible, as such there is a lot of abstract classes. Two of these are monitors which are assigned to monitor one event, and callbacks, which wrap the function pointer to be called should the event take place. The issue arises when I want to send the data that the callback needs. The data that will be sent is going to be sub-class specific (depending on the function signature) and stored in the subclassed monitor. I want to be able to pass this data along to the callback before calling execute, but since everything is abstract from the perspective of the monitor this is difficult. I'm looking for suggestions on how to do this in the best OO way possible, as of yet I haven't come up with anything I'm too fond of. Since the callbacks are sent to another class to actually be dispatched the data needs to end up inside them at some point.
For reference, the monitor abstract class
#pragma once
#include "DIVE_GUI_Types.h"
#include "DIVE_GUI_Callback.h"
#include "DIVE_GUI_Event_Dispatcher.h"
#include <map>
#include <string>
/*
Class to monitor events to be handled by the event system.
*/
class DIVE_GUI_Event_Monitor
{
private:
friend class DIVE_GUI_Kernel;
DIVE_GUI_Event_Dispatcher* m_Dispatcher;
static DIVE_HANDLE m_Active_GUI;
protected:
const std::string m_Event_ID;
std::map<DIVE_HANDLE, DIVE_GUI_Callback*> m_GUI_Map;
virtual bool Dispatch() = 0;
public:
void Update();
std::string Get_Event_ID() const { return m_Event_ID; }
DIVE_GUI_Event_Monitor(const std::string& id) : m_Event_ID(id) { }
void Add_Callback(DIVE_HANDLE, DIVE_GUI_Callback* function);
};
And the callback abstract class
#pragma once
/*
Abstract class representing a wrapper for a callback function as per the Command design pattern.
*/
class DIVE_GUI_Callback
{
public:
virtual void Excecute_Callback() const = 0;
};
Any and all opinions / suggestions are appreciated. Thanks!
If I correctly understood you, this data should be supplied to callback constructor. Suppose you have Callback1 and Callback2 derived from DIVE_GUI_Callback. So the code could look like:
DIVE_GUI_Event_Monitor* monitor;
monitor->Add_Callback(Callback1(specific_data_1));
monitor->Add_Callback(Callback2(specific_data_2));
This specific data then will be used in Excecute_Callback().