Singleton class whose ctor requires arguments - c++

I have class Command which is an instance of a class EventManager. Class Command requires two arguments(host, target) in its constructor.
class EventManager
{
public:
void Event1(){ cmd->Execute(_eventEnum); }
private:
Command *cmd;
};
class Command
{
public:
Command(Host h, Target t)
void Execute();
private:
}
Now if i need to use this method cmd->Execute() in a member function of Target class, i need to make cmd an instance variable of Target or make it global as a singleton.
I cant make cmd an instance variable of Target because it doesn't take host instance. To make it a singleton would be to add two methods like this
class Command
{
public:
CreateInstance(Host h, Target t);
GetInstance();
void Execute();
private:
Command(Host h, Target t);
}
I need to make sure that GetInstance is called after CreateInstance. Any other alternative?
Target class is a low level class with few events.
Target::LowlevelEvent()
{
cmd->Execute(lowlevelevent) //In Execute for lowlevelevent in Command class, i might call target->reset
}
Iam sorry for not being able to explain clearly. The problem is, this code has lot of events(methods), which may be in classes like EventManager or Target.
In each of these event, i would have to call a Command->Execute(). The command class requires host and target instances because they can do certain actions.
EventManager::Event1()
{
cmd->Execute(_event1);
}
Target::Event2()
{
cmd->Execute(_event2);
}
Command::Execute(Events e)
{
if (_event1 == e )
{
host->CallAction();
}
if (_event2 == e)
{
target->CallSomeOtherAction();
}
}
So now cmd needs to be an instance variable of both EventManager and Target right? Now EventManager has host and target instance which can be passed to Command ctor.
But Target doesn't have access to host. So i cant create Command instance in Target class.
So i was wondering if i create the singleton in EventManager ctor. And then call GetInstance() in Target. I know its bad idea but with this huge design, iam not able to figure out. Thanks for your help.

I really do not understand your problem, but, just from the title, I can say this: Don't use a singleton. The fact that it requires arguments is a pretty good counter-indicator for the singleton pattern.
If you want to make sure that all commands are created with the same parameters, you can provide the client with a CommandFactory that creates instances of commands.
class CommandFactory {
public:
CommandFactory(std::string host, std::string target)
: m_host(host),
m_target(target)
{}
boost::shared_ptr<Command> createCommand() {
return boost::shared_ptr<Command>(new Command(m_host, m_target));
}
private:
std::string m_host;
std::string m_target;
};
Then you could also implement some kind of object pool to reuse objects.

There is absolutely no need to make Command a singleton. Just instantiate one as you need it with the proper parameters, pass it to the manager, use it and get rid of it. You probably want to pass it, so it is a good idea to use a shared_ptr.

Related

Creating Command objects at run-time

I'm trying to write a console for a game engine which will allow me to type in commands to perform tasks, such as change the map, spawn an enemy etc.
I've been trying to do this with the Command pattern (following the example from gameprogrammingpatterns.com). See below for the outline of my current code structure.
parseCommand processes the string from the user, extracting the command name and arguments (currently using just whitespace separation). The next step is where I'm stuck. I need to create a Command* somehow to call execute on but I only have the string name of the command.
I could have a giant bunch of if statements in my parseCommand function, such as:
if (cmdName == "spawn")
return new SpawnEnemyCommand();
Alternatively I could store a pointer to each command in myConsole class, e.g. Command *spawnNewEnemy = new SpawnNewEnemy(); and then in parseCommand do if (cmdName == "spawn") spawnNewEnemy->execute();. This second option seems to be how the gameprogrammingpatterns book does it.
Neither of these options seems very practical if I end up with hundreds of console commands. I've studied all the articles and posts I can find on this pattern but it isn't helping clarify the situation for me.
How can I cleanly instantiate the correct Command object from within parseCommand?
Command interface base class:
class Command {
public:
virtual ~Command() { }
virtual void execute() = 0;
};
Example interface implementation:
class SpawnEnemyCommand : public Command {
public:
void execute() {
// method calls to perform command go here
}
};
Console class header:
class Console {
public:
Command* parseCommand(std::string);
bool validateCommand(std::string, std::vector<std::string>);
};
By relying on a dictionary (e.g, std::unordered_map or std::map) that maps a command identifier (i.e., a std::string object) to a Command object, you can design a factory with dynamic registry for your Command objects.
First, extend Command by including another virtual member function, clone(), that allows us to implement The Prototype Pattern:
class Command {
public:
// ...
virtual std::unique_ptr<Command> clone() const = 0;
};
The clone() virtual member function does what its name suggests: it clones the object. That is, SpawnEnemyCommand would override Command::clone() in the following way:
class SpawnEnemyCommand : public Command {
public:
// ...
std::unique_ptr<Command> clone() const override {
// simply create a copy of itself
return std::make_unique<SpawnEnemyCommand>(*this);
}
};
This way, your command objects can be copied polymorphically through the Command interface – i.e., you don't need to know the concrete type of the command to be copied. All you need to do to copy a Command object is to call its clone() virtual member function. For example, the following function copies the Command passed as an argument regardless of the underlying concrete type:
std::unique_ptr<Command> CopyCommand(const Command& cmd) {
return cmd.clone();
}
With this in mind, you are ready to design a factory for command objects, CommandFactory, that supports dynamically registering your command objects:
class CommandFactory {
public:
void registerCommand(std::string id, std::unique_ptr<Command>);
std::unique_ptr<Command> createCommand(std::string id) const;
private:
std::unordered_map<std::string, std::unique_ptr<Command>> registry_;
};
It all boils down to a std::unordered_map<std::string, std::unique_ptr<Command>> data member. Indexing this data member by a command identifier, which is an std::string, we retrieve a Command object – This is the prototype object we will use for cloning.
The registerCommand() member function adds a Command prototype to the registry:
void CommandFactory::registerCommand(std::string cmdId, std::unique_ptr<Command> cmd) {
registry_[cmdId] = std::move(cmd);
}
The createCommand() member function clones the Command prototype corresponding to the requested command identifier:
std::unique_ptr<Command> CommandFactory::createCommand(std::string cmdId) const {
auto const it = registry_.find(cmdId);
if (it == registry_.end())
return nullptr; // no such a command in the registry
auto const& cmdPtr = it->second;
return cmdPtr->clone();
}
As an example program:
auto main() -> int {
CommandFactory factory;
factory.registerCommand("spawn", std::make_unique<SpawnEnemyCommand>());
// ...
auto cmdPtr = factory.createCommand("spawn");
cmdPtr->execute();
}
You can also extend this factory to add support for dynamically deregistering your already-registered Command prototypes.

Calling a derived class method from the parent class' same method

My problem goes as follow: I am writing an extensible communication protocol between a server and a client. The objects needed to be transferred are using the command design pattern.
Here is the class format:
class command {
public:
using id = uint8_t;
using buffer = std::vector<char>;
enum command_t: id {a_command, another_command};
command() = delete;
command(id id): id_(id) {}
static command* unserialize(buffer);
virtual buffer const serialize() const = 0;
virtual void execute() = 0;
protected:
/* Not possible, see further where I explain. Keeping it here for
my example */
virtual static command* do_unserialize(buffer::iterator, buffer::iterator) = 0;
id id_;
};
class a_command;
class another_command;
Every command will be a subclass of command. A command_t id will be associated with every command. In the example above, a_command and another_command would have a respective class too.
command::serialize is implemented in the derived classes. What it does is it writes all the needed informations of the class in a byte array and returns it. Of course, the same thing goes for the protected command::do_unserialize - it takes a byte array and converts it to a command of the right type. But here is the problem:
The first byte of the buffer will always be the command::id associated with the good subclass.
When the server/client will receive data, it will read the command ID and then it needs to be able to unserialize it to the right command type. This is why it will need to call the static function command::unserialize and not one of the subclasses' do_unserialize.
A quick and dirty fix would be a command::unserialize looking like this:
command* command::unserialize(buffer b) {
auto it{b.begin()};
command::id const id{*it++};
switch(static_cast<command::command_t>(id)) {
case command::command_t::a_command:
return a_command::do_unserialize(it, b.end());
case command::command_t::another_command:
return another_command::do_unserialize(it, b.end());
default:
throw std::invalid_argument("command::unserialize: unknown command ID");
}
}
*** Actually not even, you cannot have a virtual static member function. So I have no idea how it could be implemented.
Even if it worked, it is not really fun, because it implies having to duplicate a line of code
for every new command created.
EDIT: A working example would be to move do_unserialize to the subclass constructor and return a pointer to the newly created object.
class derived_command: public command {
public:
derived_command(buffer::iterator beg, buffer::iterator end) {
// do_unserialize logic
}
};
// unserialize
switch (id) {
case command::command_t::derived_class: return new derived_class(b.begin(), b.end());
}
// ...
My question thus goes like this: Is there a way to dynamically link new commands only from the command::id field? A way to deduce the subclass to use from its ID? Else, is my design flawed? Is there a better way to do what I'm trying to do?
Thank you!

how to pass instanced between mutiple files and classes

Suppose i'm writing a software that it has about 50 classes.
We can divide classes into 2 part:
1. classes we forced to create instance for more that of once instance.
2. classes we just create a one instance until end of program.
So, suppose i have MainProgram class and everything do here, then just
make an instance in main.cpp and run my program.
Now, I need to pass instances created just once (option 2) to other classes, Do you
have any idea to implement to this?
Because i can't new again. i just work with old instance.For example:
I wrote a SocketNetwork Class that its constructor get port number and bind to it.
So i can't rebind again and i forced to access to resoures of the given port number.
Seems like you're looking for the singleton pattern.
It goes something like:
class A
{
public:
static A& getInstance()
{
static A a;
return a;
}
private:
A() {}
};
Because the constructor is private, you can only get the single instance of A that is created through the getInstance() method, which you can call anywhere.
`A::getInstance()`
will always return the same instance of A.
Before SingleTone, I used :
class AudioCallbackData
{
public:
AudioCallbackData();
AudioMixer *audioMixer;
AudioBuilder *AbRcv;
NetworkSocket *socketAudio;
NetworkSocket *socketCommand;
NetworkSocket *socketSetting;
NetworkSocket *socketStatus;
NetworkSocket *socketData;
MainCore *mainCorePtr;
AudioCore *audioCorePtr;
Device *devPtr;
CircularBuffer *cBuffer;
};
extern AudioCallbackData *audioCallbackDataPtr;// = ptr;
Every attribute keeps instance of a class.So for SingleTone, Now for each instance may i write a class for each instance?

C++ How can achieve this Interface configuration?

I certainly don't know how to title this question, sorry.
I'm having some problems to design the following system.
I need a class which will make some work, but this work can be done in a bunch of different ways, say that this work will be made through "drivers".
These drivers can have different interfaces and because of that I need to build a wrapper for each driver.
So I got (or I need) this:
Me ---> MainClass ----> Wrapper ----> Drivers
MainClass is the class I will touch and will call the drivers methods through different wrappers.
Here an example of usage:
MainClass worker;
worker.set_driver("driver_0");
worker.start_process(); //Start process calls a wrapper method which calls a driver's method.
To achieve this I made an interface class:
class Driver_Interface : public QObject
{
Q_OBJECT
public:
Driver_Interface(QObject* parent=0) : QObject(parent){}
virtual bool open()=0;
virtual bool close()=0;
virtual bool write()=0;
virtual bool set_config()=0;
};
A driver wrapper has this shape:
class Driver0 : public Driver_Interface
{
Q_OBJECT
public:
Driver0( QObject* parent=0);
Driver0();
bool open();
bool close();
bool write();
bool set_config();
};
Finally here comes the conflicting point, defining the MainClass:
I would like to avoid to create one member for each wrapper, so I tried this, and right now compiler doesn't complains:
class MainClass
{
public:
MainClass();
~MainClass();
void init();
void set_driver( const QString& );
void start_process();
protected:
QString driver_str;
Driver_Interface* driver; //!<--- Here Here!!!
};
When setting the driver chosen, I do this:
if( driver_str.compare("driver_0")==0 )
this->driver = new Driver_0();
Is this a valid C++ configuration or will I have problems sooner or later?
Basically, what worries me is the creation of the driver of a different type from Driver_Interface, I'm seeing that it casts automatically and no one complains...
Actually I have some problems now compiling, the infamous vtables not defined in Driver_0... does this have some relation with what I want to achieve? UPDATED: I fixed this by deleting the *Driver_Interface* constructor.
To me your basic idea seems to be fine. I would consider separating the creation of drivers into a factory (or at least a factory method) though.
This seems reasonable to me. Having a FactoryMethod or class (AbstractFactory) that creates an object of the required concrete subclass based on some config value is a common pattern.
You could consider having the MainClass implement something like
DriverInterface* createDriver(const string& driverType)
instead of encapsulating the resulting concrete DriverInterface subclass in MainClass. But if you only ever want one concrete DriverInterface instance, the above looks fine.
I would pass "driver_0" to the constructor, and call MainClass::set_driver from there. You can then make MainClass::set_driver private unless you need to change drivers.

Reconciling classes, inheritance, and C callbacks

In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries.
Consider this simplification of my design:
class BaseClass
{
public:
BaseClass() {}
~BaseClass() {}
bool init() { return doInit(); }
bool run() { return doWork(); }
void shutdown() { destroy(); }
private:
virtual bool doInit() = 0;
virtual bool doWork() = 0;
virtual void destroy() = 0;
};
And a class that inherits from it:
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass()
: BaseClass(), state_manager(new SomeOtherClass()) {}
int callbackA(int a, int b);
private:
virtual bool doInit();
virtual bool doWork();
virtual void destroy();
SomeOtherClass* state_manager;
};
// LSC.cpp:
bool LibrarySupportClass::doInit()
{
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&LibrarySupportClass::callbackA);
return true;
}
// ... and so on
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks. I would prefer doing all of these callbacks within the class because the class carries a state object.
What I ended up doing is...
static LibrarySupportClass* _inst_ptr = NULL;
static int callbackADispatch(int a, int b)
{
_inst_ptr->callbackA(a, b);
}
bool LibrarySupportClass::doInit()
{
_inst_ptr = this;
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&callbackADispatch);
return true;
}
This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice.
Is there a better way?
You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass();
~LibrarySupportClass();
static int static_callbackA(int a, int b);
int callbackA(int a, int b);
private:
//copy and assignment are rivate and not implemented
LibrarySupportClass(const LibrarySupportClass&);
LibrarySupportClass& operator=(const LibrarySupportClass&);
private:
static LibrarySupportClass* singleton_instance;
};
LibrarySupportClass.cpp
LibrarySupportClass* LibrarySupportClass::singleton_instance = 0;
int LibrarySupportClass::static_callbackA(int a, int b)
{
if (!singleton_instance)
{
WHAT? unexpected callback while no instance exists
}
else
{
return singleton_instance->callback(a, b);
}
}
LibrarySupportClass::LibrarySupportClass()
{
if (singleton_instance)
{
WHAT? unexpected creation of a second concurrent instance
throw some kind of exception here
}
singleton_instance = this;
}
LibrarySupportClass::~LibrarySupportClass()
{
singleton_instance = 0;
}
My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy).
Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class.
Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
The external constraint of the c library dictates that when your callback is called you don't have the identification of the "owning" instance of the callback. Therefore I think that your approach is correct.
I would suggest to declare the callbackDispatch method a static member of the class, and make the class itself a singleton (there are lots of examples of how to implement a singleton). This will let you implement similar classes for other libraries.
Dani beat me to the answer, but one other idea is that you could have a messaging system where the call back function dispatch the results to all or some of the instances of your class. If there isn't a clean way to figure out which instance is supposed to get the results, then just let the ones that don't need it ignore the results.
Of course this has the problem of performance if you have a lot of instances, and you have to iterate through the entire list.
The problem the way I see it is that because your method is not static, you can very easily end up having an internal state in a function that isn't supposed to have one, which, because there's a single instance on the top of the file, can be carried over between invocations, which is a -really- bad thing (tm). At the very least, as Dani suggested above, whatever methods you're calling from inside your C callback would have to be static so that you guarantee no residual state is left from an invocation of your callback.
The above assumes you have static LibrarySupportClass* _inst_ptr declared at the very top. As an alternative, consider having a factory function which will create working copies of your LibrarySupportClass on demand from a pool. These copies can then return to the pool after you're done with them and be recycled, so that you don't go around creating an instance every time you need that functionality.
This way you can have your objects keep state during a single callback invocation, since there's going to be a clear point where your instance is released and gets a green light to be reused. You will also be in a much better position for a multi-threaded environment, in which case each thread gets its own LibrarySupportClass instance.
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks
Can you elaborate? Is choosing a callback type based on userdata a problem?
Could your callback choose an instance based on a and/or b? If so, then register your library support classes in a global/static map and then have callbackADispatch() look up the correct instance in the map.
Serializing access to the map with a mutex would be a reasonable way to make this thread-safe, but beware: if the library holds any locks when it invokes your callback, then you may have to do something more clever to avoid deadlocks, depending on your lock hierarchy.