58

I was just curious where exactly the singleton pattern is used... I know how the pattern works and where it can be used but i personally never used in any real application. Can some one give an example where it can be used.. I would really appreciate if some one can explain how and where they have used in real application. Thanks, Swati

Noel M
  • 15,812
  • 8
  • 39
  • 47
swati
  • 719
  • 2
  • 7
  • 8
  • 2
    What I have learned here: don't use singleton at all. :) This pattern is not up to date due to threading and other reasons. – InsertNickHere Jul 07 '10 at 05:23
  • 9
    @InsertNickHere: It's entirely possible to implement the singleton pattern in a thread-safe manner. Testability is a much more important reason not to use singletons, IMO. – Jon Skeet Jul 07 '10 at 05:27
  • @Jon Skeet Well, I have to admit I just repeated what one told me here. I searched the comment but I can't find. They told me to use the "Application pattern" instead. – InsertNickHere Jul 07 '10 at 05:35
  • 1
    @InsertNickHere: Did they explain what the "application pattern" is? Can't say I've heard of that one... – Jon Skeet Jul 07 '10 at 05:56
  • @Jon I'm afraid I dident realy get it. It has sth to do with where is the instance created. IIRC they use a static instance in the getInstance() method or so. – InsertNickHere Jul 07 '10 at 06:08
  • @InsertNickHere threading is not so much an issue with singletons. (if they're written in a threadsafe way if needed). Other reasons might be bigger issues, other reasons being: distributed applications – Redlab Jul 07 '10 at 06:26
  • 1
    Most classes should not be thread-safe. Thread-safety is difficult to put it mildly. Therefore, adding a non-useful requirement for a class to be thread-safe is probably a poor idea. / Singletons are plain bad design. For my money the worst aspect is dependency. Any code that uses them (or uses code that uses them, etc), now has assumptions about how processes (class loaders in Java) are used. – Tom Hawtin - tackline Jul 07 '10 at 08:26
  • For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word. may be the guru jon skeet can provide example like this. – Dead Programmer Jan 19 '11 at 09:52
  • This question is old but i have to say something: For example in a game, where you have a Player you control and enemies controlled by some Kind of AI and you want to implement Sound. Isn't singleton usable here? You could have a soundmanager which loads the sounds you need (Shooting sound or damage sound...) and applies the sound-Settings (volume etc.). You can simply hold an instance of the singleton soundmanager in each object and when it shoots Play the sound. So you don't have to care about the sound Settings in every class. – Robert P Jan 20 '14 at 10:16

12 Answers12

68

Typically singletons are used for global configuration. The simplest example would be LogManager - there's a static LogManager.getLogManager() method, and a single global instance is used.

In fact this isn't a "true" singleton as you can derive your own class from LogManager and create extra instances that way - but it's typically used as a singleton.

Another example would be java.lang.Runtime - from the docs:

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

That's pretty much the definition of a singleton :)

Now the singleton pattern is mostly frowned upon these days - it introduces tight coupling, and makes things which use the singleton harder to test, as you can't easily mock out that component. If you can get away without it, so much the better. Inject your dependencies where possible instead.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 7
    @swati- You have got Guru's response... you should accept this one as answered. :) – Sumeet Jul 07 '10 at 05:59
  • You need an unhelpful definition of Singleton for `Runtime` to be one, as it has no state - it just uglifies client code. (Although you could claim that it guards mutable statics.) The Singletonness of `LogManager` is not enforced, other than by an (undocumented) circumventable permission check. – Tom Hawtin - tackline Jul 07 '10 at 08:15
  • @Sumeet I interpret the question as where Singletons are defined in application code rather than in libraries, so this answer isn't so useful. – Tom Hawtin - tackline Jul 07 '10 at 08:22
  • @Tom: In application code, I'd expect singletons in the same *sort* of areas as `LogManager`: where you effectively need global state/configuration across your whole app. But I'd generally advise against it anyway :) – Jon Skeet Jul 07 '10 at 08:27
  • @JonSkeet what about processor classes within the application .There is no state maintained , all the variables are method local . Spring by default instantiates singleton only and injects wherever necessary – Sudhakar Mar 20 '14 at 02:01
  • @Sudhakar: It may be used as a singleton by Spring, but that doesn't make it a singleton as a class. If there's no state at all, I'd be tempted to use static methods instead anyway - but it depends on whether the class is implementing an interface and whether it might conceivably need state later on. I probably wouldn't make it a *real* singleton though. – Jon Skeet Mar 20 '14 at 06:45
  • @JonSkeet yes i agree . But my argument was against the claim `the singleton pattern is mostly frowned upon these days - it introduces tight coupling, and makes things which use the singleton harder to test` . Can you provide more info on this. Thanks – Sudhakar Mar 21 '14 at 00:34
  • @Sudhakar: Well which bit do you disagree with? Spring creating a single instance and providing that to all classes is *not* really the same as the singleton pattern which *enforces* a single instance. The normal problem with the singleton pattern is that you end up with state which is hard to test against, as you can't easily start from a clean sheet. It also typically means that classes depend *directly* on the singleton, making it hard to fake it out for tests. – Jon Skeet Mar 21 '14 at 06:50
20

Some examples:

  • Hardware access
  • Database connections
  • Config files
Florian
  • 3,145
  • 1
  • 27
  • 38
15

I used the singleton pattern in an online Football Team Store System. we applied the singleton pattern to a ShoppingCart class.

You only needed one instance of the cart per an application instance. so the singleton seemed like it's the best fit for that situation.

Manaf Abu.Rous
  • 2,397
  • 21
  • 24
  • 1
    Hi, if you make ur cart class object as singleton, then the state of cart would have inconsistent results right? because multiple users will access the same cart object simultaneously. and if you make it synchronized there is a time lag for users ?. so how did you exactly make it singleton and secured state of each user individually? – Vinay Apr 30 '17 at 00:48
  • 4
    @Vinay Bro if multiple users are using the football team store, means multiple instance, BUT just a single instance for each user. Think of it as each user will be using his own computer to access the store right? so the cart will be one instance for each user respectively. EACH USER WILL HAVE HIS INSTANCE, AND WITHIN THAT INSTANCE, THE CART OBJECT WILL BE ONE. – Hyder Aug 30 '17 at 06:33
6

Consider the situation of AudioDriverService which is designed in Singleton Pattern. So we are allowed to create just a single instance of AudioDriverService class. Now actually your Windows Media Player or Youtube Player both will share the same object of AudioDriverService rather than creating a new instance.

Mr. D
  • 61
  • 1
  • 2
4

When you use Logger, you use Singleton pattern for the Logger class. In case it is not Singleton, every client will have its own Logger object and there will be concurrent access on the Logger instance in Multithreaded environment, and multiple clients will create/write to the Log file concurrently, this leads to data corruption.

Arun Raaj
  • 1,762
  • 1
  • 21
  • 20
3

For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word. may be the guru jon skeet can provide example like this.

Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
3

Singleton pattern is generally useful when the object that is created once and shared across different threads/Applications. Consider the case that you are implementing the properties load class for a printer.

Now Printers can be of variant properties. For eg:- Mono Printer, Color Printer, Automatic Scanner Support Printer and so on...

Every time on boot this config file has to load to enable a few buttons/ applications on the UI say tab or any Printer UI.

The value of the supported features are stored in form of a config table like say 1 if feature supported and 0 if not supported.

Based on the supported features we enable disable certain functionalities and application on the UI. Now this config file location in case of printers manufactured by a single company are always stored at a fixed path.

The file values would change/would be read only in the following scenarios:- 1. On Boot. 2. on Addition or deletion of any new hardware peripheral.

We can use a singleton class to implement the reading of configuration files. As the same values i.e. the config does not change on UI intervention and can be changed only on hardware intervention.

This is one example I can think of where we can implement Singleton design pattern.

netblogger
  • 31
  • 3
2

Singleton is a nice design pattern. Before deciding on the pattern first do an in depth analysis of your problem and the solution. If in your solution some object has only one instance and you want to model that in your design then you should use singleton pattern. For example if you are modelling a PC in the software there can be only one instance of a PC with respect to your running program. As Jon Skeet said java.lang.Runtime is modelled as a singleton because for all the java objects that are loaded and running inside a java runtime there is only one instance of runtime.

Again lot of times it is used for the wrong reasons. Never create a singleton so that you can easily access the object (like Object::instance() ) from anywhere without passing the object around. The is the worst use I have ever come across.

ferosekhanj
  • 1,086
  • 6
  • 11
  • 1
    Singleton is not a nice design pattern. It is tightly coupling your app and known as an anti-pattern. In fact Erich Gamma, who is one of the Gang of Four authors of the popular book "Design Pattern" is on record saying he regrets putting singleton in the book as a design pattern. – Tom Stickel Nov 09 '13 at 05:41
2

I use a media player in my android app, so I extend the mediaplayer class, and used the singleton pattern because I need only one instance, and be able to call the same instance in any other part of my app for check if is playing, or what file is current playing.

Hope it helps you, regards!!!!

1

Singleton Pattern can be used for loading the configuration , say in a web application, we are supposed to generate a file which is to be stored somewhere in the server. Now, that location can fetched from a config file(properties file) using a singleton class.since the location is to be unique and might change frequently in future, so we use a config file so as can be modified without deploying the application so as to reflect the changes and location will be global and unique through out the application

Akhil Gupta
  • 265
  • 1
  • 14
0

I used a singleton (actually a couple of them) in an application that used pureMVC. We were unhappy about the complexity this framework introduced (it became complicated and tiering to track method calls through the mvc layers). So we used a central singleton as a mediator to better separate the layers from each other.

Max Leske
  • 5,007
  • 6
  • 42
  • 54
0

Singleton Class is basically used when you have to allow only single instantiation of the class. Taking real world example, In case of OOP designing of a library, we can create library class as singleton class.