0

I know how to make a singleton class in java but what I dont understand is the concept of singleton. Like why would I need a singleton class and why would I use a singleton instead of a regular class?

"Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine."

I just read that definition but I dont get it, what does it change if there is one or more instances of a class. Why would I want to only have one instance of a class.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • in terms of memory efficiency, if you only need one object, why would you create multiple instances? – KingHodor Dec 15 '18 at 18:02
  • 3
    If the class holds state, it is important which instance you use. In general, [singletons are considered a bad idea](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons). – Andy Turner Dec 15 '18 at 18:02
  • 1
    My general advice for "why would I need this pattern?" question is: don't worry too much about it. Now that you know the pattern, you'll be able to apply it if you need it in the future. If you never end up needing it -- then you'll never end up needing it, no big deal. As for the singleton pattern specifically, a lot of people don't like it and would argue its good usages are rare. If it has state, it makes testing hard (since your tests interfere with each other, via that singleton state), and if it doesn't, then it's usually better to have static functions in a utility class. – yshavit Dec 15 '18 at 18:03
  • Lets say you have one printer and in your application you want to create manager which will handle query of documents to print. Would it be OK to let any class create its own instance of printer manager for same printer? – Pshemo Dec 15 '18 at 18:12
  • 1
    See also: Inversion of Control. Using IoC eliminates the need to use the Singleton pattern while still ensuring there is only a single instance. (And it simplifies unit testing.) – Andrew S Dec 15 '18 at 18:16

3 Answers3

0

Singletons are used for when you want exactly one instance of a class, that the entire application shares.

Good examples for this principle are classes that are in charge of accessing external resources. For example, you'd want the entire application share the same database connection (or at least connection pool), not have every class that needs it open its own connection.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Even the database example is not great. For instance, plugging that in via a singleton makes it hard to provide a mock instance for testing. – yshavit Dec 15 '18 at 18:07
  • 2
    There is a distinction between a class enforcing that only one instance existing (a singleton), and a class that you only create one instance of (it doesn't have a special name, it's just a class). There is nothing about external resources that inherently requires the enforcement: you can just create one "thing", and pass it around everywhere, without having to worry about its singleton-ness. – Andy Turner Dec 15 '18 at 18:09
0

Singletons are classes with properties which can be shared with other classes in the same context. (Application, session, ...) For example if you have to count the number of connected users in a web application. Every time a user connect, you increment a counter in a unique shared class.

0

In some cases, we need to expose a shared resource throughout the application e.g. DB connection but we don't want to

  1. create shared object up-front (before creation of client objects).
  2. explicitly pass shared object to each client object.

then we can use Singleton design pattern.

Typical Singleton class looks like

public class MySingleton {
      private MySingleton INSTANCE
      private MySingleton() {
      }

      public static MySingleton getInstance() {
       if (INSTANCE == null) {
         syncronized (MySingleton.class) {
           if (INSTANCE == null) {
             INSTANCE = new MySingleton();
           }
         }
       }
       return INSTANCE;
      }
     // instance methods exposing business operation
    }

But we can achieve the similar behaviour by making each and every instance methods which are exposing business operation as static. In this approach we don't even need to create single object.
Then why do we need Singleton?
Well, the answer is simple. To isolate actual implementation from the client. Basically we are applying abstraction OOP principle here.
This is helpful If the singleton class is part of library which is used by various clients and library wants to vary the implementation as per the client.

Sample for such singleton can be

public class MySingleton {
      private MySingleton INSTANCE
      private MySingleton() {
      }

      public static MySingleton getInstance() {
       if (INSTANCE == null) {
         syncronized (MySingleton.class) {
           if (INSTANCE == null) {
             INSTANCE = new MySingletonChild(); // here we are creating an object of subclass of MySingleton.
           }
         }
       }
       return INSTANCE;
      }
     // instance methods exposing business operation
    }

Hope this help in understanding Singleton design pattern.