35

I have read different opinions about the singleton pattern. Some maintain that it should be avoided at all costs and others that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory (let's say an object f of type F) to create objects of a certain class A. The factory is created once using some configuration parameters and then is used each time an object of type A is instantiated. So every part of the code that wants to instantiate A fetches the singleton f and create the new instance, e.g.

F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();

So the general my scenario is that

  1. I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)
  2. I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad, but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or (2) to create the factory at some point during program start up and then pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object comes so I am afraid that I would again fall back to another singleton (the object that provides my factory instance). By following back this chain of singletons I can maybe reduce the problem to one singleton (the whole application) by which all other singletons are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other unique objects and injects all other singletons at the right places) be an acceptable solution? Is this the solution that is implicitly suggested when one advises not to use singletons, or what are other solutions, e.g. in the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some, here is some more information. As explained e.g. here, the word singleton can indicate (a) a class with a single instance object and (b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and singleton pattern for (b). So, I know what the singleton pattern and dependency injection are (BTW, lately I've been using DI heavily to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from a single object living on the stack of the main method, there will always be the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and wiring depend on the main method (e.g. through some powerful DI framework that does not use the pattern itself) is the only singleton-pattern free solution.

5
  • 9
    Dependency Injection...
    – Falcon
    Commented May 8, 2012 at 6:05
  • 1
    @Falcon: Dependency Injection ... what? DI does nothing to solve this problem, though it does often give you a handy way of hiding it.
    – pdr
    Commented May 8, 2012 at 10:12
  • @Falcon do you mean IoC container? This will allow you to resolve dependencies in a single line. E.g. Dependency.Resolve<IFoo>(); or Dependency.Resolve<IFoo>().DoSomething();
    – CodeART
    Commented May 8, 2012 at 20:00
  • This is a pretty old question, and already answered. I still though it would be good to link this one: stackoverflow.com/questions/162042/… Commented Dec 5, 2012 at 7:50
  • related (possibly a duplicate): What alternatives to a singleton are there for a class which only can have one instance?
    – gnat
    Commented Apr 5, 2016 at 12:34

10 Answers 10

12

Your second option is a fine way to go -- it's a kind of dependency injection, which is the pattern used to share state across your program when you want to avoid singletons and global variables.

You can't get around the fact that something has to create your factory. If that something happens to be the application, so be it. The important point is that your factory shouldn't care what object created it, and the objects that receive the factory shouldn't depend on where the factory came from. Don't have your objects get a pointer to the application singleton and ask it for the factory; have your application create the factory and give it to those objects that will need it.

26

The purpose of a singleton is to enforce that only one instance can ever exists within a certain realm. This means that a singleton is useful if you have strong reasons to enforce singleton behavior; in practice, this is seldom the case though, and multi-processing and multi-threading certainly blur the meaning of 'unique' - is it one instance per machine, per process, per thread, per request? And does your singleton implementation take care of race conditions?

Instead of singleton, I prefer using either of:

  • short-lived local instances, e.g. for a factory: typical factory classes have minimal amounts of state, if any, and there is no real reason to keep them alive after they have served their purpose; the overhead of creating and deleting classes is nothing to worry about in 99% of all real-world scenarios
  • passing an instance around, e.g. for a resource manager: these have to be long-lived, because loading resources is expensive and you want to keep them in memory, but there is absolutely no reason to prevent further instances from being created - who knows, maybe it will make sense to have a second resource manager a few months down the road...

The reason being that a singleton is global state in disguise, which means it introduces a high degree of coupling throughout the application - any part of your code can grab the singleton instance from anywhere with minimal effort. If you use local objects or pass instances around, you have a lot more control, and you can keep your scopes small and your dependencies narrow.

1
  • 4
    This is a very good answer but I was not really asking why I should / should not use the singleton pattern. I know the troubles one can have with global state. Anyway, the topic of the question was how to have unique objects and yet a singleton-pattern free implementation.
    – Giorgio
    Commented May 8, 2012 at 19:25
6

Most people (including you) completely misunderstand what the Singleton pattern actually is. The Singleton pattern only means that one instance of a class exist and there is some mechanism for code all over the application to get a reference to that instance.

In the GoF book, the static factory method that returns a reference to a static field was just an example how that mechanism might look like, and one with severe drawbacks. Unfortunately, everyone and their dog latched onto that mechanism and thought it was what Singleton is all about.

The alternatives you cite are in fact also Singletons, just with a different mechanism for getting the reference. (2) clearly results in too much passing around, unless you need the reference in only a few places near the root of the call stack. (1) sounds like a crude dependency injection framework - so why not use a real one?

The advantage is that existing DI frameworks are flexible, powerful and well-tested. They can do much more than just manage Singletons. However, to fully use their capabilities, they work best if you to structure your application in a certain way, which is not always possible: ideally, there are central objects which are acquired through the DI framework and have all their dependencies transitively populated and are then executed.

Edit: Ultimately, everything depends on the main method anyway. But you're right: the only way to avoid the use of global/static completely is by having everything set up from the main method. Note that DI is most popular in server environments where the main method is opaque and sets up the server and application code consists basically of callbacks which are instantiated and called by the server code. But most DI frameworks also allow direct access to their central registry, e.g. Spring's ApplicationContext, for "special cases".

So basically the best thing people have come up so far is a clever combination of the two alternatives you mentioned.

6
  • Do you mean that the basic idea dependency injection is basically the first approach I sketched above (e.g. using a registry), at last the basic idea?
    – Giorgio
    Commented May 8, 2012 at 12:22
  • @Giorgio: DI always includes such a registry, but the main point that makes it better is that instead of querying the registry wherever you need an object, you have the central objects which are transitively populates, as I wrote above. Commented May 8, 2012 at 12:31
  • @Giorgio: It's easier to understand with a concrete example: let's say you have a Java EE app. Your front-end logic is in an action method of a JSF Managed Bean. When the user presses a button, the JSF container creates an instance of the Managed Bean and calls the action method. But before that, the DI component looks at the fields of the Managed Bean class, and those that have a certain annotation are populated with a reference to a Service object as per the DI configuration, and those Service objecs have the same thing happening to them. The action method can then call the services. Commented May 8, 2012 at 12:36
  • Some people (including you) do not read questions carefully and misunderstand what is actually being asked.
    – Giorgio
    Commented May 8, 2012 at 19:28
  • 2
    @Giorgio: nothing in your original question indicated that you're already familiar with dependency injection. And see updated answer. Commented May 8, 2012 at 19:53
3

There are a few alternatives:

Dependency Injection

Every object has its dependencies passed to it when it was created. Typically either a framework or a small number of factory classes are responsible for creating and wiring the objects

Service Registry

Every object is passed a service registry object. It provides methods to request various different objects which provide different services. The Android framework uses this pattern

Root Manager

There is a single object which is the root of the object graph. By following the links from this object any other object can be eventually found. Code tends to look like:

GetSomeManager()->GetRootManager()->GetAnotherManager()->DoActualThingICareAbout()
10
  • Apart from mocking, which advantage does DI have over using a singleton? This is a question that has bugged me a very long time. As for registry and root manager, aren’t they implemented as either a singleton or via DI? (In fact, the IoC container is a registry, right?) Commented May 8, 2012 at 20:33
  • 2
    @KonradRudolph, with DI the dependencies are explicit, and the object makes no assumptions about how a given resource is supplied. With singletons, the dependencies are implicit and every single use makes the assumption that there will only ever be a single such object. Commented May 8, 2012 at 21:33
  • @KonradRudolph, are the other methods implemented using Singletons or DI? Yes and No. In the end, you've either got to pass objects in or store objects in global state. But there are subtle differences in how you do this. The three version mentioned above all avoid using global state; but the manner in which the end-code gets the references is different. Commented May 8, 2012 at 21:39
  • Use of singletons assumes no single object if the singleton implements an interface (or even if not) and you pass the singleton instance to methods, instead of querying Singleton::instance everywhere in client code. Commented May 9, 2012 at 11:00
  • @KonradRudolph, then you are really using some hybrid Singleton/DI approach. My purist side thinks you should go for a pure DI approach. However, most of the issues with singleton don't really apply there. Commented May 9, 2012 at 14:33
1

If your needs from the singleton can be boiled down to a single function, why not just use a simple factory function? Global functions (probably a static method of class F in your example) are inherently singletons, with uniqueness enforced by the compiler and linker.

class Factory
{
public:
    static Object* createObject(...);
};

Object* obj = Factory::createObject(...);

Admittedly, this breaks down when the operation of the singleton cannot be reduced to a single function call, though perhaps a small set of related functions might get you by.

All that being said, items 1 and 2 in your question make it clear that you really just want one of something. Depending on your definition of the singleton pattern, you are either already using it or very close. I don't think you can have one of something without it being a singleton or at least very close to one. It's just too close to the meaning of singleton.

As you suggest, at some point you have to have one of something, so perhaps the problem is not having a single instance of something, but of taking steps to prevent (or at least discourage or minimize) abuse of it. Moving as much state out of the "singleton" and into parameters as possible is a good start. Narrowing the interface to the singleton also helps, as there are fewer opportunities for abuse that way. Sometimes you just have to suck it up and make the singleton very robust, like the heap or the filesystem.

2
  • 4
    Personally I see this as just a different implementation of the singleton pattern. In this case the singleton instance is the class itself. Specifically: it has all the same drawbacks as a "real" singleton. Commented May 8, 2012 at 6:03
  • @Randall Cook: I think your answer captures my point. I read very often that the singleton is very very bad and should be avoided at all costs. I agree on this but on the other hand I think that it is technically impossible to always avoid it. When you need "one of something" you have to create it somewhere and access it in some way.
    – Giorgio
    Commented May 18, 2012 at 17:13
1

If you are using a multiparadigm language like C++ or Python, one alternative to a singleton class is a set of functions/variables wrapped in a namespace.

Conceptually speaking, a C++ file with free global variables, free global functions, and static variables used for information hiding, all wrapped in a namespace, gives you nearly the same effect as a singleton "class".

It only breaks down if you want inheritance. I've seen a lot of singletons that would have been better off this way.

0

Singletons Encapsulation

Case scenario. Your application is Object Oriented, and requires 3 or 4 specific singletons, even if you have more classes.

Before Example (C++ like pseudocode):

// network info
class Session {
  // ...
};

// current user connection info
class CurrentUser {
  // ...
};

// configuration upon user
class UserConfiguration {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfiguration {
  // ...
};

One way is to partially remove some (global) singletons, by encapsulating all of them into a unique singleton, that has as members, the other singletons.

This, way, instead of the "several singletons, approach, versus, no singleton at all, approach", we have the "encapsulate all singletons into one, approach".

After Example (C++ like pseudocode):

// network info
class NetworkInfoClass {
  // ...
};

// current user connection info
class CurrentUserClass {
  // ...
};

// configuration upon user
// favorite options menues
class UserConfigurationClass {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfigurationClass {
  // ...
};

// this class is instantiated as a singleton
class SessionClass {
  public: NetworkInfoClass NetworkInfo;
  public: CurrentUserClass CurrentUser;
  public: UserConfigurationClass UserConfiguration;
  public: TerminalConfigurationClass TerminalConfiguration;

  public: static SessionClass Instance();
};

Please note, that the examples are more like pseudocode, and ignore minor bugs, or syntax errors, and consider the solution to the question.

There is also other thing to consider, because, the programming language used, may affect how to implement your singleton or non singleton implementation.

Cheers.

0

Your original requirements:

So the general my scenario is that

  1. I need only one instance of a class either for optimization reasons (I do not need >multiple factory objects) or for sharing common state (e.g. the factory knows how many >instances of A it can still create)
  2. I need a way to have access to this instance f of F in different places of the code.

Do not line up with the definition of a singleton (and what you rather refer to later). From GoF (my version is 1995) page 127:

Ensure a class only has one instance, and provide a global point of access to it.

If you only need one instance, that does not preclude you from making more.

If you want a single, globally accessible instance then make a single globally accessible instance. There is no need to have a pattern named for everything you do. And yes, single globally accessible instances are usually bad. Giving them a name doesn't make them less bad.

To avoid global accessibility, the common 'make an instance and pass it along' or 'have the owner of two objects glue them together' approaches work well.

0

How about using IoC container? With some thought you can end up with something on the lines of:

Dependency.Resolve<IFoo>(); 

You would have to specify which implementation of IFoo to use at a startup, but this is a one off configuration which you can easily replace later. Lifetime of a resolved instance can be normally controlled by an IoC container.

Static singleton void method could be replaced with:

Dependency.Resolve<IFoo>().DoSomething();

Static singleton getter method could be replaced with:

var result = Dependency.Resolve<IFoo>().GetFoo();

Example is relevant to .NET, but I'm certain very similar can be achieved in other languages.

0

It depends very much what you mean by singleton. My definition: A “singleton instance” (not class) is an object that serves a specific purpose, that should be exclusively used for that purpose, that is automatically created the first time it is needed or earlier, and stays in existence as long as the program runs.

The usual method to get a singleton instance is to call a function or class method which returns the singleton instance. That method can return an instance of a subclass of the declared type, or an instance of any class supporting some interface. You can safely store references to singleton instances or pass them around, including to constructors, which allows dependency injection.

You definitely don’t use static class instances (they get destructed before the application ends, and they prevent changing the class without changing all your code).

And the big one: Don’t use singleton instances when you use two or more. In ios 16 you can have one process that looks like it is running multiple instances of an application. So objects referring to an application as a whole cannot be singletons anymore. Or simpler, you cannot have a singleton representing your printer if you have two printers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.