What can't a namespace do that a singleton class does? [duplicate] - c++

Edit:
From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).
So the main questions that need to be answered are:
When should you use a Singleton
How do you implement a Singleton correctly
My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.
So get the ball rolling:
I will hold my hand up and say this is what I use but probably has problems.
I like "Scott Myers" handling of the subject in his books "Effective C++"
Good Situations to use Singletons (not many):
Logging frameworks
Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
OK. Lets get some criticism and other implementations together.
:-)

Answer:
Use a Singleton if:
You need to have one and only one object of a type in system
Do not use a Singleton if:
You want to save memory
You want to try something new
You want to show off how much you know
Because everyone else is doing it (See cargo cult programmer in wikipedia)
In user interface widgets
It is supposed to be a cache
In strings
In Sessions
I can go all day long
How to create the best singleton:
The smaller, the better. I am a minimalist
Make sure it is thread safe
Make sure it is never null
Make sure it is created only once
Lazy or system initialization? Up to your requirements
Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
Provide a destructor or somehow figure out how to dispose resources
Use little memory

Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.
A singleton gives you:
Global access to an object, and
A guarantee that no more than one object of this type can ever be created
Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we really need it.
Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write
std::ostream os;
os << "hello world\n";
When you intended to write
std::cout << "hello world\n";
Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.
If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.
The "only one instance is possible" constraint doesn't really protect us against likely bugs. But it does make our code very hard to refactor and maintain. Because quite often we find out later that we did need more than one instance. We do have more than one database, we do have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.
So a singleton should be used if and only if, we need both the traits it offers: If we need global access (which is rare, because globals are generally discouraged) and we need to prevent anyone from ever creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.
If you need global access to an object, make it a global, like std::cout. But don't constrain the number of instances that can be created.
If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.
If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.

The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.

One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.

Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.
Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static
C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.
Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.
So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.

Modern C++ Design by Alexandrescu has a thread-safe, inheritable generic singleton.
For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static get() function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.

How do you implement a Singleton correctly
There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the "singleton".
The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.

As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.
Some useful aspects of singletons:
lazy or upfront instantiation
handy for an object which requires setup and/or state
However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.
Finally, a factory lends itself to dependency injection technologies like Spring etc.

The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.

Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.
If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.

The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).
So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.

Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.

Because a singleton only allows one instance to be created it effectively controls instance replication. for example you'd not need multiple instances of a lookup - a morse lookup map for example, thus wrapping it in a singleton class is apt. And just because you have a single instance of the class does not mean you are also limited on the number of references to that instance. You can queue calls(to avoid threading issues) to the instance and effect changes necessary. Yes, the general form of a singleton is a globally public one, you can certainly modify the design to create a more access restricted singleton. I haven't tired this before but I sure know it is possible.
And to all those who commented saying the singleton pattern is utterly evil you should know this: yes it is evil if you do not use it properly or within it confines of effective functionality and predictable behavior: do not GENERALIZE.

But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.

Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:
#include<iostream>
#include<mutex>
using namespace std;
std::mutex mtx;
class MySingleton{
private:
static MySingleton * singletonInstance;
MySingleton();
~MySingleton();
public:
static MySingleton* GetInstance();
MySingleton(const MySingleton&) = delete;
const MySingleton& operator=(const MySingleton&) = delete;
MySingleton(MySingleton&& other) noexcept = delete;
MySingleton& operator=(MySingleton&& other) noexcept = delete;
};
MySingleton* MySingleton::singletonInstance = nullptr;
MySingleton::MySingleton(){ };
MySingleton::~MySingleton(){
delete singletonInstance;
};
MySingleton* MySingleton::GetInstance(){
if (singletonInstance == NULL){
std::lock_guard<std::mutex> lock(mtx);
if (singletonInstance == NULL)
singletonInstance = new MySingleton();
}
return singletonInstance;
}
Regarding the situations where we need to use singleton classes can be-
If we want to maintain the state of the instance throughout the execution of the program
If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on.
It will be appreciable if anybody can suggest optimisation in my above code.

I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.

I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.
I'm sure there are other solutions but I find this one very useful and easy to implement.

Anti-Usage:
One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.

I think this is the most robust version for C#:
using System;
using System.Collections;
using System.Threading;
namespace DoFactory.GangOfFour.Singleton.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 server requests
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class LoadBalancer
{
private static LoadBalancer instance;
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Lock synchronization object
private static object syncLock = new object();
// Constructor (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
instance = new LoadBalancer();
}
}
}
return instance;
}
// Simple, but effective random load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
Here is the .NET-optimised version:
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Singleton.NETOptimized
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Confirm these are the same instance
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 requests for a server
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// Singleton
sealed class LoadBalancer
{
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly LoadBalancer instance =
new LoadBalancer();
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Note: constructor is private.
private LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
return instance;
}
// Simple, but effective load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
You can find this pattern at dotfactory.com.

The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.
A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.
Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.
Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).
With that in mind, GOAs can be initialised like this:
namespace {
T1 * pt1 = NULL;
T2 * pt2 = NULL;
T3 * pt3 = NULL;
T4 * pt4 = NULL;
}
int main( int argc, char* argv[])
{
T1 t1(args1);
T2 t2(args2);
T3 t3(args3);
T4 t4(args4);
pt1 = &t1;
pt2 = &t2;
pt3 = &t3;
pt4 = &t4;
dostuff();
}
T1& getT1()
{
return *pt1;
}
T2& getT2()
{
return *pt2;
}
T3& getT3()
{
return *pt3;
}
T4& getT4()
{
return *pt4;
}
It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).
As for when I use singletons? I used them for 2 things
- A singleton table that indicates what libraries have been loaded with dlopen
- A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.

I still don't get why a singleton has to be global.
I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.
I don't see why this functionality would be bad.

If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).
Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...

In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !

Another implementation
class Singleton
{
public:
static Singleton& Instance()
{
// lazy initialize
if (instance_ == NULL) instance_ = new Singleton();
return *instance_;
}
private:
Singleton() {};
static Singleton *instance_;
};

Related

Is there a rule of thumb to decide where to store my classes (i.e. what type of memory)?

Suppose I have a c++ program which with several classes which are related like this:
class Application
{
public:
// some functions
private:
BusinessLogic businessLogic;
// some variables
};
class BusinessLogic
{
public:
// some functions
private:
BusinessLogicSubClass1 businessLogicSubClass1;
BusinessLogicSubClass2 businessLogicSubClass2;
// some other member variables
};
BusinessLogicSubClass1
{
public:
// some functions
private:
SubClassOfSubClass1 subClassOfSubClass1;
// some other member variables
};
// etc.... (you get the idea I hope)
The point is, I know at compile time that there is an Application class that contains the BusinessLogic class which contains many sub classes. I also know that I only need one instance of the Application class. Now the question is how to decide on where to store such a class in memory?
As far as I know there are three main possibilities:
on the stack:
int main()
{
Application application;
// do something with application
return 0;
}
on the heap:
int main()
{
std::unique_ptr application = std::make_unique&ltApplication&gt();
// do something with application
return 0;
}
as a static:
int main()
{
static Application application;
// do something with application
return 0;
}
I read some information on the different types of memory. Based on what I read, I think it is not the best decision to store the application class on the stack. Mainly because the stack has a limited size and there is a very limited advantage of having the stack's automatic memory management (i.e. cleaning up variables that go out of scope) in this case.
I find it harder to decide however how to make the trade of between static and heap memory. In the simplified example above I think I go with static, because everything is known at compile time and static memory is said to be more efficient, compared to heap memory. (Does this way of thinking make any sense, or am I overlooking something here?)
However, there are some examples in which the choice becomes less evident. Suppose the application needs to be initialized via an .ini file. If you store the instance of the Application class on the heap, it will be possible to pass the initialization values via the constructor:
int main
{
IniFileReader reader;
InitializationValues iniValues = reader.GetIniValues();
std::unique_ptr application = std::make_unique&ltApplication2&gt(iniValues);
// do something with application
return 0;
}
As far as I know, constructor initialization is considered to be better in terms of design than using some Init function like this:
int main
{
static Application3 application;
IniFileReader reader;
InitializationValues iniValues = reader.GetIniValues();
application.Init(iniValues);
// do something with application
return 0;
}
So here the choice is between cleaner code or a more efficient program. I realize this is sort of trade off is very much dependent on what type of application you intend to build.
What I am looking for is, if there are perhaps some rules of thumb or a sort of flow chart to decide where to store your classes?
Some (not necessarily good) examples of such rules could be:
if you know everything about a class at compile time and you know there is only one instance, try to always store it as a static.
always use the heap for objects that are shared between different threads.
it does not really matter in this or that case, so chose for cleaner code.
And secondly, are there any general guidelines or design principles on where to put the static classes? I find it hard to decide where to put a static class if they need to be accessed by more than one other class. Globals are generally considered bad design for instance.
A practical example of such a dilemma, can be found in the following article on the state design pattern: https://gameprogrammingpatterns.com/state.html --> see subsection static states
I am not sure if the authors choice to put a static instance of each state in the base class is the best design. He also admits to put them there "for no particular reason". Any suggestions for a better place? Make a sort of state-database class? Make a singleton of each state?
edit: changed mistake in code pointed out by Neil Butterworth
One very common way to handle your situation is to use a Singleton design pattern. you can find lots of good references on stack overflow, or via a simple google search. Take a look at this one for example. For you it would look something like this:
class Application
{
public:
static Application& getInstance()
{
static Application instance;
return instance;
}
private:
Application() {}
...
};
For dynamic parameters, I'm not sure I would agree that it's always better to initialize in the constructor, but the details really matter for this. There are cases where it does make sense, and cases where it doesn't. In the singleton case you almost always need some sort of separate "Init" call since you don't want to pass construction arguments on every call to getInstance().
To your question about "heap" versus "static". Assuming you really are only creating one Application instance, and you're running on a "desktop" OS like Linux/Window/MacOS, there will be no meaningful difference in runtime performance between these two. Uninitialized static variables are usually placed in .bss, and the first thing the OS will do when launching your process is dynamically allocate a bunch of pages to make space for the various data sections in your program. Not a whole lot different from what you're doing in code (i.e. a one-time dynamic memory allocation).

Why singleton classes cannot be sub-classed?

I was going through the negative effects of singleton. Here is one of the point that I cannot understand at all. Here is the link and the point.
Negative sides of Singleton
The following points are used against the Singleton pattern:
They deviate from the Single Responsibility Principle. A singleton class has the responsibility to create an instance of itself along
with other business responsibilities. However, this issue can be
solved by delegating the creation part to a factory object.
Singleton classes cannot be sub classed.
http://www.codeproject.com/Articles/307233/Singleton-Pattern-Positive-and-Negative-Aspects
The article seems to be mostly written about the normal Java implementation of singleton, where the constructor is private; that means subclassing is impossible (the subclass is required to call the constructor, but can't). Allowing more access to the singleton means it can no longer be guaranteed to have only a single instance.
It's really an inherent contradiction; if you can subclass, then you can trivially create more instances (by just creating an otherwise empty subclass for each instance you want) so you don't really have a singleton.
Buy or borrow a copy of GoF
The original GoF book says the following in the Implementation part of Singleton. Note: Instance is the same as the Java getInstance().
Ensuring a unique instance [...]
Subclassing the Singleton class. The main issue is not so much defining the subclass but installing its unique instance so that clients will be able to use it. In essence, the variable that refers to the singleton instance must get initialized with an instance of the subclass. The simplest technique is to determine which singleton you want to use in the Singleton's Instance operation. An example in the Sample Code shows how to implement this technique with environment variables. Another way to chose the subclass of Singleton is to take the implementation of Instance out of the parent class and put it in the subclass. That lets a C++ programmer decide the class of singleton at link-time (e.g., by linking in an object file containing a different implementation) but keeps it hidden from the clients of the singleton. The link approach fixes the choice of singleton class at link-time, which makes it hard to choose the singleton class at run-time. Using conditional statements to determine the subclass is more flexible, but it hard-wires the set of possible Singleton classes. Neither approach is flexible enough in all cases. A more flexible approach uses a registry of singletons. Instead of having Instance define the set of possible Singleton classes, the Singleton classes can register their singleton instance by name in a well-known registry.The registry maps between string names and singletons. When Instance needs a singleton, it consults the registry, asking for the singleton by name.
The GoF book goes on to show how registries work.
Here's the Sample Code using the environment variable:
Now let's consider what happens when there are subclasses... We'll select the [subtype] through an environment variable [...]
MazeFactory* MazeFactory::Instance () {
if (_instance == 0) {
const char* mazeStyle = getenv("MAZESTYLE");
if (strcmp(mazeStyle, "bombed") == 0 {
_instance = new BombedMazeFactory;
} else if (strcmp(mazeStyle, "enchanted") == 0) }
_instance = new EnchantedMazeFactory;
// ... other possible subclasses
} else { // default
_instance = new MazeFactory;
}
}
return _instance;
}

Singleton class - Which method

I have implemented two methods of how I think a Singleton class should be implemented, I just want the opinion of programmers to which one is the best method to use.
Each of the methods uses these classes:
class Animal {
public:
virtual void speak() const = 0;
};
class Dog {
virtual void speak() { cout << "Woof!!"; }
};
First method:
class AnimalFactory {
public:
static Animal* CreateInstance(int theTypeOfAnimal);
private:
AnimalFactory() { };
static int count; // this will be used to count the number of objects created
static int maxCount; // this is the max count allowed.
};
int AnimalFactory::count = 0;
int AnimalFactory::maxCount = 1;
Animal* AnimalFactory::CreateInstance(int theTypeOfAnimal)
{
Animal* pAnimal = NULL;
if(pAnimal != NULL)
{
return pAnimal;
}
switch(theTypeOfAnimal)
{
case 0:
pAnimal = new Dog();
count++;
break;
case 1:
pAnimal = new Cat();
count++;
break;
case 2:
pAnimal = new Spider();
count++;
break;
default:
cout << "Not known option";
}
return pAnimal;
}
Second Method:
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
Any opinion would be grateful, thanks :)!
In the majority of the cases, Singleton is abused. The general advice is: Don't use it! If you think you really have a case where a Singleton is the correct solution: Probability is still against you. If you are really, really sure you need to use a Singleton, you probably still want to use it as some sort of glorified data: don't. It is gonna hurt you.
OK, you have been warned.
The second approach has the distinct advantage with C++ 2011 that it i thread safe. It also happens to be simpler.
If you are stuck with a compiler not, yet, implementing the C++ 2011 logic and you use your Singleton in a multi-threaded application, you'll need to make sure that it only gets initialized once even if the access function is called concurrently from two threads. Of course, this leads to something else which doesn't work: Do not use the double-checked locking pattern. It [also] doesn't work. If you implemented so that it works, someone will come along and "fix" your code.
Anyway, in embedded environment, you don't need singleton pattern, you don't even need new or malloc.
It's hard to explain, but I try.
Embedded systems must work. There is no IT department armed with manuals and FAQs and internet forums, nobody will tune your Linux system, nobody will fix your config, nobody will install a larger hard disk or memory according to task's needs. Your program can't write a detailed message to stderr and exit() with meaningful error code, if it can, it just means that your embedded system does not work. If you can flash a red led on error, it's better than nothing, but it's still means: device failed.
I think, it's a good practice not to use malloc/free and new/delete. You should "pre-allocate" possible maximum number of objects by defining them as static arrays. Or, if the maximum number of items depends on a configuration which the user can change, you should allocate the fixed number of objects just as program starts, so low memory issue turns out on startup, not half an hour later.
Yes, lot of memory will be wasted, but there will be no mysterious errors. And you have not to deal with memory issues in your program (only at startup).
The first code snippet fails to implement a singleton because AnimalFactory::CreateInstance fails to check the instance count that it maintains.
The second code snippet,
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
when done properly, is called a Meyers' singleton, after Scott Meyers.
The code as given would work but yields awkward usage. To avoid having to instantiate Singleton, the instance method should be declared static. Also, the requirement on classType classes that they should only instantiable by Singleton, should be documented, e.g. as a comment with an example.
Others have already warned you against using singletons, but let me also do that.
Singletons have their uses, such as ensuring that e.g. a Windows API "window class" is only created once, but mainly they're abused as global-variables-in-disguise. One problem with global variables, namely that you don't know when a global variable has been initialized (in C++ programming known as the static initialization order fiasco), is avoided by singletons. However, the main problem, that they serve as spaghetti communication systems, routing chaos-inducing information in untraceable ways between places you would never suspect, is still there.
So, don't.
But if you at some time find that you absolutely need singletons, e.g. for a logging facility, then please do read up on the discussion of singletons in Andrei Alexandrescu's "Modern C++ Design", and then get hold of the Loki library and let it do the job for you.
It looks like you could spare yourself a whole heap of headache by just making a function:
Animal * CreateAnimal(int theTypeOfAnimal)
{
static int count = 0;
static int maxCount = 1;
switch(theTypeOfAnimal)
{
// ...
}
}
Well, the first one doesn't work:
Animal* pAnimal = NULL;
if(pAnimal != NULL)
{
return pAnimal;
}
Do you expect the condition to ever hold?
I've seen the second one before, so I'll go ahead and say it's more idiomatic, at least for this type of singleton, which isn't really a singleton per-say because you have multiple instances, albeit one-per-actual-type. Well, the general idea is okay (for a singleton), but I'd go with something like:
template<typename classType>
class AnimalManager {
public:
static Animal& instance()
{
static classType object;
return object;
}
};
which you could call
Animal& animal = AnimalManager<Dog>::instance();
//assuming you derive Dog from Animal, which you're currently not
I will be downwoted by masses of the Java programmers, but I don't mind: If you know, that your program needs exactly one object instance, feel free to create a global object and write a static get() method which returns (the reference to) it (and don't reference to the global object from elsewhere).
I think, singleton pattern in Java is a technique to implement the global object, in C++ is a technique to hide the global object. But why, it's just as ugly when hidden, as ugly as it's not hidden.
You should also wrap it carefully, in order to make it appear on the scene as other normal objects, and handle it as normal objects. Maybe, later, as the program evolves, there will be more instances of them, and you'll be happy that it already acts as a normal object.
The first solution has some odd coding (see Luchian Grigore answer). Ignoring that:
It is some mix of concepts between a factory and a singleton.
A factory normally is a singleton but what it emits normally is not.
The second one does ensure that you can only create one object of a class, but only iff you wrap it in the Singleton template. If the class has a public constructor, you can create it outside the scheme and thus break the rules.
In my book neither of these is a good way to do a singleton.
To expand a bit: The idea of the singleton is to because you need to manage some specific thing and you need one component to be wholly responsible.
With your first version you can have multiple factories that each create one animal. Doesn't make sense in the real world, doesn't make sense in code.
Your second example tries to allow every call to (optionally) be a singleton - but not all classes need to be, and many will not necessarily behave when "singletonized".
In review, John Vlisides said if one 'pattern' shouldn't have made it into his GOF book it was the singleton. However, also see his discussion of implementing it in C++.
See also Andrei Alexandrescu who explores singletons with 3 different creation models, 4 different lifetime models and 2 threading models, that's 24 ways of implementing a singleton.
Personally, I go out of my way to avoid them by only passing around objects that are needed. It makes testing easier, makes interfaces explicit, etc. You've been warned, of course you've been warned, but will you listen?

C++ singleton vs. global static object

A friend of mine today asked me why should he prefer use of singleton over global static object?
The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)
What are the advantages one over the other? (in C++)
Actually, in C++ preferred way is local static object.
Printer & thePrinter() {
static Printer printer;
return printer;
}
This is technically a singleton though, this function can even be a static method of a class. So it guaranties to be constructed before used unlike with global static objects, that can be created in any order, making it possible to fail unconsistently when one global object uses another, quite a common scenario.
What makes it better than common way of doing singletons with creating new instance by calling new is that object destructor will be called at the end of a program. It won't happen with dynamically allocated singleton.
Another positive side is there's no way to access singleton before it gets created, even from other static methods or from subclasses. Saves you some debugging time.
In C++, the order of instantiation of static objects in different compilation units is undefined. Thus it's possible for one global to reference another which is not constructed, blowing up your program. The singleton pattern removes this problem by tying construction to a static member function or free function.
There's a decent summary here.
A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)
A static global object can have state in C# as well:
class myclass {
// can have state
// ...
public static myclass m = new myclass(); // globally accessible static instance, which can have state
}
What are the advantages one over the other? (in C++)
A singleton cripples your code, a global static instance does not.
There are countless questions on SO about the problems with singletons already. Here's one, and another, or another.
In short, a singleton gives you two things:
a globally accessible object, and
a guarantee that only one instance can be created.
If we want just the first point, we should create a globally accessible object.
And why would we ever want the second? We don't know in advance how our code may be used in the future, so why nail it down and remove what may be useful functionality? We're usually wrong when we predict that "I'll only need one instance". And there's a big difference between "I'll only need one instance" (correct answer is then to create one instance), and "the application can't under any circumstances run correctly if more than one instance is created. It will crash, format the user's harddrive and publish sensitive data on the internet" (the answer here is then: Most likely your app is broken, but if it isn't, then yes, a singleton is what you need)
Reason 1:
Singletons are easy to make so they are lazy build.
While you can do this with globals it take extra work by the developer. So by default globals are always initialized (apart from some special rules with namespaces).
So if your object is large and/or expensive to build you may not want to build it unless you really have to use it.
Reason 2:
Order of initialization (and destruction) problem.
GlobalRes& getGlobalRes()
{
static GlobalRes instance; // Lazily initialized.
return instance;
}
GlobalResTwo& getGlobalResTwo()
{
static GlobalResTwo instance; // Lazy again.
return instance;
}
// Order of destruction problem.
// The destructor of this object uses another global object so
// the order of destruction is important.
class GlobalResTwo
{
public:
GlobalResTwo()
{
getGlobalRes();
// At this point globalRes is fully initialized.
// Because it is fully initialized before this object it will be destroyed
// after this object is destroyed (Guaranteed)
}
~GlobalResTwo()
{
// It is safe to use globalRes because we know it will not be destroyed
// before this object.
getGlobalRes().doStuff();
}
};
Another benefit of the Singleton over the global static object is that because the constructor is private, there is a very clear, compiler enforced directive saying "There can only be one".
In comparison, with the global static object, there will be nothing stopping a developer writing code that creates an additional instance of this object.
The benefit of the extra constraint is that you have a guarantee as to how the object will be used.
Using Singleton("construct on first use") idiom, you can avoid static initialization order fiasco
In C++, there's not a huge amount of difference between the two in terms of actual usefulness. A global object can of course maintain its own state (possibly with other global variables, though I don't recommend it). If you're going to use a global or a singleton (and there are many reasons not to), the biggest reason to use a singleton over a global object is that with a singleton, you can have dynamic polymorphism by having several classes inheriting from a singleton base class.
OK, there are two reasons to go with a singleton really. One is the static order thing everyone's talking about.
The other is to prevent someone from doing something like this when using your code:
CoolThing blah;
gs_coolGlobalStaticThing = blah;
or, even worse:
gs_coolGlobalStaticThing = {};
The encapsulation aspect will protect your instance from idiots and malicious jerks.

Singleton: How should it be used

Edit:
From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).
So the main questions that need to be answered are:
When should you use a Singleton
How do you implement a Singleton correctly
My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.
So get the ball rolling:
I will hold my hand up and say this is what I use but probably has problems.
I like "Scott Myers" handling of the subject in his books "Effective C++"
Good Situations to use Singletons (not many):
Logging frameworks
Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
OK. Lets get some criticism and other implementations together.
:-)
Answer:
Use a Singleton if:
You need to have one and only one object of a type in system
Do not use a Singleton if:
You want to save memory
You want to try something new
You want to show off how much you know
Because everyone else is doing it (See cargo cult programmer in wikipedia)
In user interface widgets
It is supposed to be a cache
In strings
In Sessions
I can go all day long
How to create the best singleton:
The smaller, the better. I am a minimalist
Make sure it is thread safe
Make sure it is never null
Make sure it is created only once
Lazy or system initialization? Up to your requirements
Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
Provide a destructor or somehow figure out how to dispose resources
Use little memory
Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.
A singleton gives you:
Global access to an object, and
A guarantee that no more than one object of this type can ever be created
Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we really need it.
Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write
std::ostream os;
os << "hello world\n";
When you intended to write
std::cout << "hello world\n";
Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.
If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.
The "only one instance is possible" constraint doesn't really protect us against likely bugs. But it does make our code very hard to refactor and maintain. Because quite often we find out later that we did need more than one instance. We do have more than one database, we do have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.
So a singleton should be used if and only if, we need both the traits it offers: If we need global access (which is rare, because globals are generally discouraged) and we need to prevent anyone from ever creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.
If you need global access to an object, make it a global, like std::cout. But don't constrain the number of instances that can be created.
If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.
If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.
The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.
One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.
Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.
Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static
C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.
Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.
So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.
Modern C++ Design by Alexandrescu has a thread-safe, inheritable generic singleton.
For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static get() function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.
How do you implement a Singleton correctly
There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the "singleton".
The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.
As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.
Some useful aspects of singletons:
lazy or upfront instantiation
handy for an object which requires setup and/or state
However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.
Finally, a factory lends itself to dependency injection technologies like Spring etc.
The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.
Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.
If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.
The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).
So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.
Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.
Because a singleton only allows one instance to be created it effectively controls instance replication. for example you'd not need multiple instances of a lookup - a morse lookup map for example, thus wrapping it in a singleton class is apt. And just because you have a single instance of the class does not mean you are also limited on the number of references to that instance. You can queue calls(to avoid threading issues) to the instance and effect changes necessary. Yes, the general form of a singleton is a globally public one, you can certainly modify the design to create a more access restricted singleton. I haven't tired this before but I sure know it is possible.
And to all those who commented saying the singleton pattern is utterly evil you should know this: yes it is evil if you do not use it properly or within it confines of effective functionality and predictable behavior: do not GENERALIZE.
But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.
Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:
#include<iostream>
#include<mutex>
using namespace std;
std::mutex mtx;
class MySingleton{
private:
static MySingleton * singletonInstance;
MySingleton();
~MySingleton();
public:
static MySingleton* GetInstance();
MySingleton(const MySingleton&) = delete;
const MySingleton& operator=(const MySingleton&) = delete;
MySingleton(MySingleton&& other) noexcept = delete;
MySingleton& operator=(MySingleton&& other) noexcept = delete;
};
MySingleton* MySingleton::singletonInstance = nullptr;
MySingleton::MySingleton(){ };
MySingleton::~MySingleton(){
delete singletonInstance;
};
MySingleton* MySingleton::GetInstance(){
if (singletonInstance == NULL){
std::lock_guard<std::mutex> lock(mtx);
if (singletonInstance == NULL)
singletonInstance = new MySingleton();
}
return singletonInstance;
}
Regarding the situations where we need to use singleton classes can be-
If we want to maintain the state of the instance throughout the execution of the program
If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on.
It will be appreciable if anybody can suggest optimisation in my above code.
I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.
I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.
I'm sure there are other solutions but I find this one very useful and easy to implement.
Anti-Usage:
One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.
I think this is the most robust version for C#:
using System;
using System.Collections;
using System.Threading;
namespace DoFactory.GangOfFour.Singleton.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 server requests
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class LoadBalancer
{
private static LoadBalancer instance;
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Lock synchronization object
private static object syncLock = new object();
// Constructor (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
instance = new LoadBalancer();
}
}
}
return instance;
}
// Simple, but effective random load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
Here is the .NET-optimised version:
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Singleton.NETOptimized
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Confirm these are the same instance
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 requests for a server
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// Singleton
sealed class LoadBalancer
{
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly LoadBalancer instance =
new LoadBalancer();
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Note: constructor is private.
private LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
return instance;
}
// Simple, but effective load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
You can find this pattern at dotfactory.com.
The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.
A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.
Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.
Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).
With that in mind, GOAs can be initialised like this:
namespace {
T1 * pt1 = NULL;
T2 * pt2 = NULL;
T3 * pt3 = NULL;
T4 * pt4 = NULL;
}
int main( int argc, char* argv[])
{
T1 t1(args1);
T2 t2(args2);
T3 t3(args3);
T4 t4(args4);
pt1 = &t1;
pt2 = &t2;
pt3 = &t3;
pt4 = &t4;
dostuff();
}
T1& getT1()
{
return *pt1;
}
T2& getT2()
{
return *pt2;
}
T3& getT3()
{
return *pt3;
}
T4& getT4()
{
return *pt4;
}
It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).
As for when I use singletons? I used them for 2 things
- A singleton table that indicates what libraries have been loaded with dlopen
- A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.
I still don't get why a singleton has to be global.
I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.
I don't see why this functionality would be bad.
If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).
Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...
In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !
Another implementation
class Singleton
{
public:
static Singleton& Instance()
{
// lazy initialize
if (instance_ == NULL) instance_ = new Singleton();
return *instance_;
}
private:
Singleton() {};
static Singleton *instance_;
};