<p>Name the design considerations in deciding between use of a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton</a> versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)</p>

[{'answer_id': 46542, 'author': 'David J. Sokol', 'author_id': 1390, 'author_profile': 'https://Stackoverflow.com/users/1390', 'pm_score': -1, 'selected': False, 'text': '<p>When the single class needs state.  Singletons maintain a global state, static classes do not.</p>\n\n<p>For instance, making a helper around a registry class:  If you have  changable hive (HKey Current User vs. HKEY Local Machine) you could go:</p>\n\n<pre><code>RegistryEditor editor = RegistryEditor.GetInstance();\neditor.Hive = LocalMachine\n</code></pre>\n\n<p>Now any further calls to that singleton will operate on the Local Machine hive.  Otherwise, using a static class, you would have to specify that Local Machine hive everytiem, or have a method like <code>ReadSubkeyFromLocalMachine</code>.</p>\n'}, {'answer_id': 46547, 'author': 'xanadont', 'author_id': 1886, 'author_profile': 'https://Stackoverflow.com/users/1886', 'pm_score': 3, 'selected': False, 'text': '<p>I\'d argue the only difference is syntax:  MySingleton.Current.Whatever() vs MySingleton.Whatever().  The state, as David mentioned, is ultimately "static" in either case.</p>\n\n<hr>\n\n<p>EDIT: The bury brigade came over from digg ... anyhow, I thought of a case that would require a singleton.  Static classes cannot inherit from a base class nor implement an interface (at least in .Net they cannot).  So if you require this functionality then you must use a singleton.</p>\n'}, {'answer_id': 46553, 'author': 'Tim Frey', 'author_id': 1471, 'author_profile': 'https://Stackoverflow.com/users/1471', 'pm_score': 2, 'selected': False, 'text': '<p>If by "static class" you mean a class that has only static variables, then they actually can maintain state.  My understanding is the that the only difference would be how you access this thing.  For example:</p>\n\n<pre><code>MySingleton().getInstance().doSomething();\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>MySingleton.doSomething();\n</code></pre>\n\n<p>The internals of MySingleton will obviously be different between them but, thread-safety issues aside, they will both perform the same with regards to the client code.</p>\n'}, {'answer_id': 46560, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 1, 'selected': False, 'text': '<p>Singletons should never be used (unless you consider a class with no mutable state a singleton). "static classes" should have no mutable state, other than perhaps thread-safe caches and the like.</p>\n\n<p>Pretty much any example of a singleton shows how not to do it.</p>\n'}, {'answer_id': 46566, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': "<p>If a singleton is something you can dispose of, to clean up after it, you can consider it when it's a limited resource (ie. only 1 of it) that you don't need all the time, and have some kind of memory or resource cost when it is allocated.</p>\n\n<p>The cleanup code looks more natural when you have a singleton, as opposed to a static class containing static state fields.</p>\n\n<p>The code, however, will look kind of the same either way so if you have more specific reasons for asking, perhaps you should elaborate.</p>\n"}, {'answer_id': 46567, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 0, 'selected': False, 'text': "<p>The two can be quite similar, but remember that the true Singleton must <em>itself</em> be instantiated (granted, once) and then served. A PHP database class that returns an instance of <code>mysqli</code> is not really a Singleton (as some people call it), because it is returning an instance of another class, not an instance of the class that has the instance as a static member.</p>\n\n<p>So, if you're writing a new class that you plan to allow only one instance of in your code, you might as well write it as a Singleton. Think of it as writing a plain-jane class and adding to it to facilitate the single-instantiation requirement. If you're using someone else's class that you can't modify (like <code>mysqli</code>), you should be using a static class (even if you fail to prefix its definition with the keyword).</p>\n"}, {'answer_id': 46587, 'author': 'newdayrising', 'author_id': 3126, 'author_profile': 'https://Stackoverflow.com/users/3126', 'pm_score': 0, 'selected': False, 'text': "<p>Singletons are more flexible, which can be useful in cases where you want the Instance method to return different concrete subclasses of the Singleton's type based on some context.</p>\n"}, {'answer_id': 46608, 'author': 'rp.', 'author_id': 2536, 'author_profile': 'https://Stackoverflow.com/users/2536', 'pm_score': 0, 'selected': False, 'text': "<p>Static classes can't be passed around as arguments; instances of a singleton can be. As mentioned in other answers, watch for threading issues with static classes.</p>\n\n<p>rp</p>\n"}, {'answer_id': 47027, 'author': 'Landon Kuhn', 'author_id': 1785, 'author_profile': 'https://Stackoverflow.com/users/1785', 'pm_score': 0, 'selected': False, 'text': '<p>A singleton may have a constructor and destructor. Depending on your language, the constructor may be called automatically the first time your singleton is used, or never if your singleton is not used at all. A static class would have no such automatic initialization.</p>\n\n<p>Once a reference to a singleton object is obtained, it can be used just like any other object. The client code may not even need to know its using a singleton if a reference to the singleton is stored earlier on:</p>\n\n<pre><code>Foo foo = Foo.getInstance();\ndoSomeWork(foo); // doSomeWork wont even know Foo is a singleton\n</code></pre>\n\n<p>This obviously makes things easier when you choose to ditch the Singleton pattern in favor of a real pattern, like IoC.</p>\n'}, {'answer_id': 47035, 'author': 'Jared Updike', 'author_id': 2543, 'author_profile': 'https://Stackoverflow.com/users/2543', 'pm_score': 0, 'selected': False, 'text': '<p>Use the singleton pattern when you need to compute something at runtime that you would compute at compile time if you could, like lookup tables.</p>\n'}, {'answer_id': 47037, 'author': 'izb', 'author_id': 974, 'author_profile': 'https://Stackoverflow.com/users/974', 'pm_score': 2, 'selected': False, 'text': '<p>Think of a singleton like a service. It\'s an object which provides a specific set of functionality. E.g.</p>\n\n<pre><code>ObjectFactory.getInstance().makeObject();\n</code></pre>\n\n<p>The object factory is an object which performs a specific service.</p>\n\n<p>By contrast, a class full of static methods is a collection of actions that you might want to perform, organised in a related group (The class). E.g.</p>\n\n<pre><code>StringUtils.reverseString("Hello");\nStringUtils.concat("Hello", "World");\n</code></pre>\n\n<p>The StringUtils example here is a collection of functionality that can be applied anywhere. The singleton factory object is a specific type of object with a clear responsibility that can be created and passed around where required.</p>\n'}, {'answer_id': 47064, 'author': 'newdayrising', 'author_id': 3126, 'author_profile': 'https://Stackoverflow.com/users/3126', 'pm_score': 3, 'selected': False, 'text': '<p>One of my favorite discussions about this issue is <a href="http://web.archive.org/web/20080118174633/http://www.bitchwhocodes.com/archives/2006/04/singleton_vs_st.html" rel="nofollow noreferrer">here</a> (original site down, now linked to <a href="http://www.archive.org/web/web.php" rel="nofollow noreferrer">Internet Archive Wayback Machine</a>.)</p>\n\n<p>To summarize the flexibility advantages of a Singleton:</p>\n\n<ul>\n<li>a Singleton can be easily converted\ninto a factory</li>\n<li>a Singleton can be easily\nmodified to return different\nsubclasses</li>\n<li>this can result in a more maintainable application</li>\n</ul>\n'}, {'answer_id': 47067, 'author': 'dmo', 'author_id': 1807, 'author_profile': 'https://Stackoverflow.com/users/1807', 'pm_score': 2, 'selected': False, 'text': '<p>Static classes are instantiated at runtime.  This could be time consuming.  Singletons can be instantiated only when needed.</p>\n'}, {'answer_id': 48797, 'author': 'Jagmal', 'author_id': 4406, 'author_profile': 'https://Stackoverflow.com/users/4406', 'pm_score': 0, 'selected': False, 'text': '<p>I think a place where Singleton will make more sense than the static class is when you have to construct a pool of costly resources (like database connections). You would not be interested in creating the pool if noone ever uses them (static class will means that you do the costly work when class is loaded).</p>\n'}, {'answer_id': 48896, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 3, 'selected': False, 'text': '<p>A static class with a load of static variables is a bit of a hack.</p>\n\n<pre><code>/**\n * Grotty static semaphore\n **/\n public static class Ugly {\n\n   private static int count;\n\n   public synchronized static void increment(){\n        count++;\n   }\n\n   public synchronized static void decrement(){\n        count--;\n        if( count&lt;0 ) {\n            count=0;\n        }\n   }\n\n   public synchronized static boolean isClear(){\n         return count==0;    \n\n    }\n   }\n</code></pre>\n\n<p>A singleton with an actual instance is better.</p>\n\n<pre><code>/**\n * Grotty static semaphore\n **/\n public static class LessUgly {\n   private static LessUgly instance;\n\n   private int count;\n\n   private LessUgly(){\n   }\n\n   public static synchronized getInstance(){\n     if( instance==null){\n        instance = new LessUgly();\n     }\n     return instance;\n   }\n   public synchronized void increment(){\n        count++;\n   }\n\n   public synchronized void decrement(){\n        count--;\n        if( count&lt;0 ) {\n            count=0;\n        }\n   }\n\n   public synchronized boolean isClear(){\n         return count==0;    \n\n    }\n   }\n</code></pre>\n\n<p>The state is in ONLY in the instance.</p>\n\n<p>So the singleton can be modified later to do pooling, thread-local instances etc.\nAnd none of the already written code needs to change to get the benefit.</p>\n\n<pre><code>public static class LessUgly {\n       private static Hashtable&lt;String,LessUgly&gt; session;\n       private static FIFO&lt;LessUgly&gt; freePool = new FIFO&lt;LessUgly&gt;();\n       private static final POOL_SIZE=5;\n       private int count;\n\n       private LessUgly(){\n       }\n\n       public static synchronized getInstance(){\n         if( session==null){\n            session = new Hashtable&lt;String,LessUgly&gt;(POOL_SIZE);\n            for( int i=0; i &lt; POOL_SIZE; i++){\n               LessUgly instance = new LessUgly();  \n               freePool.add( instance)\n            }\n         }\n         LessUgly instance = session.get( Session.getSessionID());\n         if( instance == null){\n            instance = freePool.read();\n         }\n         if( instance==null){\n             // TODO search sessions for expired ones. Return spares to the freePool. \n             //FIXME took too long to write example in blog editor.\n         }\n         return instance;\n       }     \n</code></pre>\n\n<p>It\'s possible to do something similar with a static class but there will be per-call overhead in the indirect dispatch.</p>\n\n<p>You can get the instance and pass it to a function as an argument. This lets code be directed to the  "right" singleton. We know you\'ll only need one of it... until you don\'t.</p>\n\n<p>The big benefit is that stateful singletons can be made thread safe, whereas a static class cannot, unless you modify it to be a secret singleton.</p>\n'}, {'answer_id': 151332, 'author': 'Tobias', 'author_id': 14027, 'author_profile': 'https://Stackoverflow.com/users/14027', 'pm_score': 7, 'selected': True, 'text': "<ul>\n<li>Singletons can implement interfaces and inherit from other classes.</li>\n<li>Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.</li>\n<li>Singletons offer an actual object.</li>\n<li>Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.</li>\n</ul>\n"}, {'answer_id': 655587, 'author': 'yfeldblum', 'author_id': 12349, 'author_profile': 'https://Stackoverflow.com/users/12349', 'pm_score': 2, 'selected': False, 'text': '<p>Singletons should not be used in the same way as static classes. In essense,</p>\n\n<pre><code>MyStaticClass.GetInstance().DoSomething();\n</code></pre>\n\n<p>is essentially the same as</p>\n\n<pre><code>MyStaticClass.DoSomething();\n</code></pre>\n\n<p>What you should actually be doing is <em>treating the singleton as just another object</em>. If a service requires an instance of the singleton type, then pass that instance in the constructor:</p>\n\n<pre><code>var svc = new MyComplexServce(MyStaticClass.GetInstance());\n</code></pre>\n\n<p>The service should not be aware that the object is a singleton, and should treat the object as just an object.</p>\n\n<p>The object can certainly be implemented, as an implementation detail and as an aspect of overall configuration, as a singleton if that makes things easier. But the things that use the object should not have to know whether the object is a singleton or not.</p>\n'}, {'answer_id': 655640, 'author': 'KitsuneYMG', 'author_id': 86515, 'author_profile': 'https://Stackoverflow.com/users/86515', 'pm_score': 0, 'selected': False, 'text': '<p>A singleton is also a good idea if you want to force efficient caching of data. for example, I have a class that looks up definitions in an xml document. Since parsing the document can take a while, I set up a cache of definitions (I use SoftReferences to avoid outOfmemeoryErrors). If the desired definition is not in the cache I do the expensive xml parsing. Otherwise I return a copy from the cache. Since having multiple caches would mean I still might have to load the same definition multiple times, I need to have a static cache. I choose to implement this class as a singleton so that I could write the class using only normal (non-static) data members. This allows me to still create an istantiation of the class should I need it for some reason (serialization, unit testing, etc.)</p>\n'}, {'answer_id': 2088246, 'author': 'TrueWill', 'author_id': 161457, 'author_profile': 'https://Stackoverflow.com/users/161457', 'pm_score': 4, 'selected': False, 'text': '<p>How about "avoid both"? Singletons and static classes:</p>\n\n<ul>\n<li>May introduce global state</li>\n<li>Get tightly coupled to multiple other classes</li>\n<li>Hide dependencies</li>\n<li>Can make unit testing classes in isolation difficult</li>\n</ul>\n\n<p>Instead, look into <a href="http://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a> and <a href="http://martinfowler.com/articles/injection.html">Inversion of Control Container</a> libraries. Several of the IoC libraries will handle lifetime management for you.</p>\n\n<p>(As always, there are exceptions, such as static math classes and C# extension methods.)</p>\n'}, {'answer_id': 4264358, 'author': 'Mayank', 'author_id': 518442, 'author_profile': 'https://Stackoverflow.com/users/518442', 'pm_score': 2, 'selected': False, 'text': '<p>Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. One example can be state codes.</p>\n'}, {'answer_id': 15880377, 'author': 'Amegon', 'author_id': 738126, 'author_profile': 'https://Stackoverflow.com/users/738126', 'pm_score': 0, 'selected': False, 'text': '<p>Singleton is like a service, as already mentioned. Pro is its flexibility.\nStatic, well, you need some static parts in order to implement Singleton.</p>\n\n<p>Singleton has code to take care of instantiation of th actual object, which can be a great help if you run into racing problems. In a static solution you may need to deal with racing problems at multiple code locations.</p>\n\n<p>However, same as Singleton can be constructed with some static variables, you may be able to compare it with \'goto\'. It can bevery useful for building other structures, but you really need to know how to use it and should not \'overuse\' it. Therefore general recommendation is to stick to Singleton, and use static if you have to.</p>\n\n<p>also check the other post: <a href="https://stackoverflow.com/questions/1321352/why-choose-a-static-class-over-a-singleton-implementation?lq=1">Why choose a static class over a singleton implementation?</a></p>\n'}, {'answer_id': 31503153, 'author': 'Ram', 'author_id': 3805988, 'author_profile': 'https://Stackoverflow.com/users/3805988', 'pm_score': 0, 'selected': False, 'text': '<p>refer <a href="http://codeofdoom.com/wordpress/2008/04/20/how-and-when-to-use-singleton-classes/" rel="nofollow">this</a></p>\n\n<p>summary:</p>\n\n<p>a. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.</p>\n\n<p>b. use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, lot of n/w calls(connection pool) ..etc. To make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening</p>\n'}]
['https://Stackoverflow.com/questions/46541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3594/']