I wrote 2 classes, Agent and Timing. The third class will contain the main() function and manage it all. The goal is to create n instances of Agent and a SINGLE instance of Timing. It’s important to mention that Agent uses Timing fields and Timing uses Agent functions.
How can I turn Timing to singleton?
//Agent.h
#ifndef Timing_h
#define Timing_h
#include <string>
#include "Timing.h"
class Agent{
public:
Agent(std::string agentName);
void SetNextAgent(Agent* nextAgent);
Agent* GetNextAgent();
void SendMessage();
void RecieveMessage(double val);
// static Timing runTime;
What I thought would solve my problem but I got:
‘Timing’ does not name a type
~Agent();
private:
std::string _agentName;
double _pID;
double _mID;
Agent* _nextAgent;
};
#endif
//Timing.h
#ifndef Timing_h
#define Timing_h
class Timing{
private:
typedef struct Message{
Agent* _agent;
double _id;
}Message;
typedef Message* MessageP;
Message** _messageArr;
static int _messagesCount;
public:
Timing();
void AddMessage(Agent* agent, double id);
void LeaderElected(string name);
void RunTillWinnerElected();
~Timing();
};
#endif
Is this really the way to create a singleton and if it is what is the problem?
And if not, how can I turn it to a singleton?
The most conventional way to create a singleton has following requirements:
1) The constructor should be private and a static interface shall be provided which in turn creates a static object of the singleton class (which is a member of the class itself) and return it. Basically provide a global point of access.
2) You have to decide in advance if you want the users of the class to be able to extend it and design your class to support it if required.
If the above two requirements are met, there are a number of ways a singleton can be designed including the ones which would work with multi threaded applications.