While ago I read about not allowing defining further instances of one object. But I cannot find that article again. Could anybody tell me how to prevent defining any other object from class CLog
?
class CLog
{
........
} log;
While ago I read about not allowing defining further instances of one object. But I cannot find that article again. Could anybody tell me how to prevent defining any other object from class CLog
?
class CLog
{
........
} log;
An alternative solution to a singleton is to use the Service Locator
pattern.
A good description of it and how to use it is described in http://gameprogrammingpatterns.com/service-locator.html.
Again like the singleton this pattern should be used sparingly however a logging system can be a good use case for it and if nothing else it teaches you some new design patterns.
Make your constructor as private. Define one public method which returns instance of class.
class sample{
private:
sample(){};
static *sample instance;
public:
static *sample getInstance(){
if (instance != null)
instance = new sample();
return instance;
}
getInstance() method creates class instance before creating it checks whether the instance exists, if it exists it retuns the existing one otherwise creates new one.In this way you can make your class to create single instance of class. As constructor is private no one can create objects using constructor.