When should a singleton be used instead of a static class?

What are the design considerations when choosing between singleton and static class? At the same time, you are, as it were, forced to oppose them, so any contrasts that you can come up with are also useful for showing your thought process! In addition, each interviewer likes to see illustrative examples. :)

+82
design-patterns
Sep 05 '08 at 18:48
source share
22 answers
  • Singletons can implement interfaces and inherit from other classes.
  • Singlets can be lazily loaded. Only when it is really necessary. This is very convenient if initialization involves expensive resource loading or database connections.
  • Singlets offer a real object.
  • Singletones can be expanded in the factory. Managing objects behind the scenes is abstract, so it is better maintained and provides better code.
+78
Sep 30 '08 at 0:43
source share

How about getting around both? Singletones and static classes:

  • May enter global state
  • Connect tightly to several other classes
  • Hide dependencies
  • Can make module testing classes isolated complex

Instead, check out the Injection Dependency and Inversion of Control Container libraries. Some of the IoC libraries will work with you to manage your life cycle.

(As always, there are exceptions, such as static math classes and C # extension methods.)

+13
Jan 18 '10 at 18:27
source share

I would say that the only difference is the syntax: MySingleton.Current.Whatever () vs MySingleton.Whatever (). The state, as David said, is ultimately "static."




EDITOR: A similar gang came from digg ... anyway, I thought of a case that would require a singleton. Static classes cannot inherit from the base class and cannot implement an interface (at least in .Net they cannot). Therefore, if you require this feature, you should use singleton.

+8
Sep 05 '08 at 18:51
source share

One of my favorite discussions on this issue is here (the source site down, now linked to the Internet Way Way Machine .

To summarize the benefits of Singleton's flexibility:

  • Singleton can be easily converted to factory
  • Singleton can be easily modified to return different subclasses
  • this can lead to more convenient use
+7
Sep 05 '08 at 23:16
source share

A static class with a load of static variables is a bit hacked.

/** * Grotty static semaphore **/ public static class Ugly { private static int count; public synchronized static void increment(){ count++; } public synchronized static void decrement(){ count--; if( count<0 ) { count=0; } } public synchronized static boolean isClear(){ return count==0; } } 

The syntax with the actual instance is better.

 /** * Grotty static semaphore **/ public static class LessUgly { private static LessUgly instance; private int count; private LessUgly(){ } public static synchronized getInstance(){ if( instance==null){ instance = new LessUgly(); } return instance; } public synchronized void increment(){ count++; } public synchronized void decrement(){ count--; if( count<0 ) { count=0; } } public synchronized boolean isClear(){ return count==0; } } 

The state is ONLY in the instance.

This way singleton can be modified later to do pooling, streaming local instances, etc. And not one of the code already written needs to be changed in order to benefit.

 public static class LessUgly { private static Hashtable<String,LessUgly> session; private static FIFO<LessUgly> freePool = new FIFO<LessUgly>(); private static final POOL_SIZE=5; private int count; private LessUgly(){ } public static synchronized getInstance(){ if( session==null){ session = new Hashtable<String,LessUgly>(POOL_SIZE); for( int i=0; i < POOL_SIZE; i++){ LessUgly instance = new LessUgly(); freePool.add( instance) } } LessUgly instance = session.get( Session.getSessionID()); if( instance == null){ instance = freePool.read(); } if( instance==null){ // TODO search sessions for expired ones. Return spares to the freePool. //FIXME took too long to write example in blog editor. } return instance; } 

You can do something similar with a static class, but there will be overhead in indirect dispatch.

You can get an instance and pass it to the function as an argument. This allows you to pass the code to the "right" singleton. We know that you only need one of them ... until you do.

The big advantage is that state-based syntaxes can be thread-safe, while a static class cannot, unless you change it to a secret singleton.

+5
Sep 07 '08 at 23:30
source share

Think of singlet as a service. This is an object that provides a specific set of functions. For example.

 ObjectFactory.getInstance().makeObject(); 

A factory object is an object that executes a specific service.

In contrast, a class full of static methods is a set of actions that you might want to perform, organized in a related group (class). For example.

 StringUtils.reverseString("Hello"); StringUtils.concat("Hello", "World"); 

The StringUtils example provides a set of functions that can be applied anywhere. A singleton factory object is a specific type of object with a clear responsibility that can be created and transferred where necessary.

+4
Sep 05 '08 at 22:58
source share

Static classes are created at runtime. This can be time consuming. Singletones can only be created when necessary.

+4
Sep 05 '08 at 23:22
source share

Singletones should not be used in the same way as static classes. In fact,

 MyStaticClass.GetInstance().DoSomething(); 

essentially coincides with

 MyStaticClass.DoSomething(); 

What you really have to do is treat the singleton as just another object. If the service requires an instance of a singleton type, pass this instance in the constructor:

 var svc = new MyComplexServce(MyStaticClass.GetInstance()); 

The service does not need to know that the object is single, and should consider the object as just an object.

The object, of course, can be implemented as an implementation detail and as one of the aspects of the general configuration, as a singleton, if this simplifies the situation. But things that use an object do not need to know whether the object is single or not.

+4
Mar 17 '09 at 18:50
source share

If by "static class" you mean a class that has only static variables, then they can actually maintain state. I understand that the only difference is how you access this thing. For example:

 MySingleton().getInstance().doSomething(); 

against

 MySingleton.doSomething(); 

The internals of MySingleton will obviously differ from each other, but problems from the point of view of security aside, they will perform the same actions regarding the client code.

+2
Sep 05 '08 at 18:52
source share

The Singleton pattern is typically used to serve independent or static instance data when multiple threads can access data at the same time. One example would be a status code.

+2
Nov 24 '10 at 7:25
source share

Singletones should never be used (unless you are considering a class without a singleton mutable state). "static classes" should not have a mutable state, except, possibly, thread-safe caches, etc.

Almost any singleton example shows how not to do this.

+1
Sep 05 '08 at 18:54
source share

If a singleton is something that you can destroy, clean up after it, you can consider it when it is a limited resource (i.e. only 1 of them) that you don't need all the time, and have some kind of memory or resource when it is allocated.

The cleanup code looks more natural if you have a singleton rather than a static class containing static status fields.

The code, however, will look the same anyway, so if you have more specific reasons for the request, you might need to clarify.

0
Sep 05 '08 at 18:58
source share

Both can be very similar, but remember that a true Singleton must itself be created (provided, once) and then served. The PHP database class that returns the mysqli instance is not really Singleton (as some people call it), because it returns an instance of another class, not an instance of the class with the instance as a static member.

So, if you are writing a new class that you plan to allow only one instance of code, you can write it as Singleton. Think about this by writing a simple jane class and adding to it to ease the requirement of instantiating. If you are using another class that cannot be changed (e.g. mysqli ), you should use a static class (even if you do not prefix its definition with a keyword).

0
Sep 05 '08 at 18:59
source share

Singletones are more flexible, which can be useful when you want the instance method to return different concrete subclasses of type Singleton based on some context.

0
Sep 05 '08 at 19:05
source share

Static classes cannot be passed as arguments; instances of a single singlet may be. As mentioned in other answers, watch out for streaming issues with static classes.

gr

0
Sep 05 '08 at 19:10
source share

The syntax can have a constructor and a destructor. Depending on your language, the constructor may be called automatically the first time you use a single singlet, or never if your singleton is not used at all. A static class would not have such automatic initialization.

As soon as a link to a singleton object is received, it can be used in the same way as any other object. Client code may not even know its use of a singleton if the link to the singleton is stored earlier:

 Foo foo = Foo.getInstance(); doSomeWork(foo); // doSomeWork wont even know Foo is a singleton 

This obviously makes things easier when you choose a Singleton template in favor of a real template such as IoC.

0
Sep 05 '08 at 22:50
source share

Use the singleton pattern when you need to compute something at runtime that you could compile at compile time if you could, like lookup tables.

0
Sep 05 '08 at 22:58
source share

I think the place where Singleton will make more sense than the static class is when you need to build a pool of expensive resources (like connecting to a database). You would not be interested in creating a pool if no one ever uses them (a static class means that you do expensive work when loading a class).

0
Sep 07 '08 at 21:19
source share

Syntax is also a good idea if you want to achieve efficient data caching. for example, I have a class that is looking for definitions in an XML document. Since parsing the document may take some time, I set up the definition cache (I use SoftReferences to avoid outOfmemeoryErrors). If the desired definition is not in the cache, I am doing expensive xml parsing. Otherwise, I am returning a copy from the cache. Since having multiple caches will mean that I still have to load the same definition multiple times, I need to have a static cache. I decided to implement this class as singleton so that I can write the class using only regular (non-static) data elements. This allows me to still create an istantiation of the class if I need it for any reason (serialization, unit testing, etc.).

0
Mar 17 '09 at 19:14
source share

Singleton is like a service, as already mentioned. Pro is its flexibility. Static, well, for implementing Singleton you need some static parts.

Singleton has a code that should take care of creating the actual object, which can be a big help if you run into racing problems. In a static solution, you may have to run into racing issues in several places in the code.

However, like Singleton, you can build some static variables, you can compare it with 'goto'. This may be useful for creating other structures, but you really need to know how to use it, and you should not “abuse” it. Therefore, the general recommendation is to stick with Singleton and use static if you need to.

also check another message: Why choose a static class compared to a singleton implementation?

0
Apr 08 '13 at 13:28
source share

send this

Summary:

but. One simple rule of thumb that you can follow is that you do not need to maintain state, you can use the Static class, otherwise you must use Singleton.

b. use Singleton if this is a particularly "heavy" object. If your object is large and occupies a reasonable amount of memory, there are a lot of n / a calls (connection pool) .. etc. To make sure that it will not be created multiple times. The Singleton class will help prevent this from happening.

0
Jul 19 '15 at 16:03
source share

If one class requires state. Singletones support global state; static classes do not.

For example, creating an assistant around a registry class: if you have a mutable bush (HKey Current User or HKEY Local Machine), you can go:

 RegistryEditor editor = RegistryEditor.GetInstance(); editor.Hive = LocalMachine 

Now, any further calls to this singleton will work on the local computer bush. Otherwise, using a static class, you will need to indicate that each bush is a local machine, or a method similar to ReadSubkeyFromLocalMachine .

-one
Sep 05 '08 at 18:48
source share



All Articles