11

every one know how to write code for Singleton Design Pattern.say for example

public class Singleton  
{  
    // Private static object can access only inside the Emp class.  
    private static Singleton instance;  

    // Private empty constructor to restrict end use to deny creating the object.  
    private Singleton()  
    {  
    }  

    // A public property to access outside of the class to create an object.  
    public static Singleton Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                instance = new Singleton();  
            }  
            return instance;  
        }  
    }  
}  

it is very clear that when we create a instance of any class many time the memory is allocated for each instance but in case of Singleton design pattern a single instance give the service for all calls.

1) i am bit confuse and really do nor realize that what are the reasons...that when one should go for Singleton Design Pattern. only for saving some memory or any other benefit out there.

2) suppose any single program can have many classes then which classes should follow the Singleton Design Pattern? what is the advantage of Singleton Design Pattern?

3 in real life apps when should one make any classes following Singleton Design Pattern? thanks

Here is thread safe singleton

public sealed class MultiThreadSingleton   
{   
    private static volatile MultiThreadSingleton instance;   
    private static object syncRoot = new Object();   

    private MultiThreadSingleton()   
    {   
    }   

    public static MultiThreadSingleton Instance   
    {   
        get   
        {   
            if (instance == null)   
            {   
                lock (syncRoot)   
                {   
                    if (instance == null)   
                    {   
                        instance = new MultiThreadSingleton();   
                    }   
                }   
            } 

        return instance;   
        }   
    }   
}
cuongle
  • 74,024
  • 28
  • 151
  • 206
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 10
    Just as an aside, your example isn't thread-safe - it's an example of how *not* to implement the singleton pattern unless you *really* don't care about thread safety. – Jon Skeet Oct 15 '12 at 18:28
  • yes i know it is not thread safe. i just need to know when one should design of his classes like above one. what is the advantages are there for singleton design patten – Thomas Oct 15 '12 at 18:39
  • http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton – Habib Oct 15 '12 at 18:40
  • 3
    My point is that if you're going to write "every one know how to write code for Singleton Design Pattern" then showing *bad* code is a bad idea... – Jon Skeet Oct 15 '12 at 18:40
  • 1
    yes my question updated for thread safe singleton class design. thanks – Thomas Oct 15 '12 at 18:43
  • IMO, having any code in this question is a distraction. The actual question is valid. – Austin Salonen Oct 15 '12 at 19:06

9 Answers9

11

To assure only one and same instance of object every time.

Take a scenario, say for a Company application, there is only one CEO. If you want to create or access CEO object, you should return the same CEO object every time.

One more, after logging into an application, current user must return same object every time.

sgud
  • 422
  • 2
  • 7
9

Other answers are good, as well. But they are providing examples of behavioural characteristics of the pattern. But, Singleton is more about creation. Thus one of the most important benefit of the pattern is that it is resource friendly. You are not wasting memory for a new object when you actually do not need a new one.

This causes another benefit, which is the instantiation overhead is avoided.

ozgur
  • 2,549
  • 4
  • 25
  • 40
4

Benefits of Singleton Pattern:

• Instance control: Singleton prevents other objects from instantiating their own copies of the Singleton object, ensuring that all objects access the single instance.

• Flexibility: Since the class controls the instantiation process, the class has the flexibility to change the instantiation process.

The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.

Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
3

Real time usages/benefits of Singleton Design Pattern.

  1. While using multi-threading, to manage the multi-thread Pool.
  2. to manage the "service host repositories" in SOA (service oriented architecture).
  3. for Logging Framework implementation
  4. in automation Testing/Unit Testing project i.e. Coded UI projects.
  5. While implementing the Caching in a big application.
  6. for configuration settings to make proper control over the application.
2

One useful place to use a singleton is if it is accessing some resource that you only want to have a single access point for. For example, I've used it when writing some code to talk to a device. I only want one piece of code talking to the device so I use a singleton. Any attempt to create another instance of the object that talks to the device will just give you the same object back so I never have to worry about two instances maintaining out-of-sync data about the device or getting messages to and from the device mixed up or out-of-order.

But, of course, you are under no obligation to use them. They are just a tool that is sometimes useful.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

Generally singleton is considered an anti-pattern in OOP because it means a class is asserting that with respect to the entire program - which in OOP it should have no knowledge of - it knows it's going to be the only one. That being said, singleton is the proper way to implement a constant in my experience. In general if something I was about to hard-code into a program (say a database username) then it can be moved to a Config file or a singleton.

One of few areas Java beats C# (in my opinion...) is its support for enums. Java offers truly OO constants via enums, and so this is how I will always implement a singleton in Java. C# has no ready-equivalent.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 2
    I think it's a stretch to say that "Generally singleton is considered an anti-pattern..." That implies that it's considered an design anti-pattern more often than a design pattern. I don't know whether it's true or not, but anecdotally this is the first time I've heard Singleton called an anti-pattern. If it was a wide-spread consideration I would have expected to have at least heard it before even if I wasn't paying much attention (which is likely) to discussions of the Singleton pattern. – Adam Porad Oct 15 '12 at 18:47
  • @AdamPorad http://en.wikipedia.org/wiki/Singleton_pattern (6 references), http://stackoverflow.com/questions/11292109/why-is-singleton-considered-an-anti-pattern-in-java-world-sometimes, http://stackoverflow.com/questions/1448393/singleton-design-pattern-pitfalls links a google tech talk. – djechlin Apr 03 '14 at 12:14
0

It can improve the way that memory is handled in the JVM and with memory being used properly, better performance will be reached. You are not creating multiple objects but trying to create only one, that way, there is less work for the Garbage collector and less memory occupation in the JVM heap.

tagus
  • 129
  • 1
  • 5
0

for me i use singleton when i dont want to always getting data from my database if its not necessary. for example i created a singleton class for getting the data from my database once and only once, and use that data across my system, then i expose a method that will get the data(refresh) again when necessary or get the data when theres a new/modified data.

dev1.L
  • 1
  • I believe this is where a cache system is for. Implement the cache-aside pattern to get values from cache and if not initialize the values (for a certain amount of time). – Eduard Keilholz Oct 19 '22 at 07:32
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32951792) – Attila T Oct 22 '22 at 12:05
-1

Let us assume there is one printer and all have to access that printer then while creating an object u should give access to only one person to print as it doesnt allow another person at the same time thats why in this situations in real life we need single ton classes where we can manage the tasks one by one with better clarity...