-2

I understand the singleton design pattern concept, but I never really come across implementing singleton pattern in java applications or web based applications. So tell me where we are using this approach in real time applications.

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
pradeep
  • 295
  • 4
  • 17

2 Answers2

2

As described by the pattern, any time you want there to exist only a single instance of something, you would use the Singleton Pattern.

A common example might be a Logger object. There could be many places throughout the system where one would invoke a logger to, well, log something. But you may only ever need one such instance. This can be particularly true if constructing the instance is a heavy operation.

Something like this:

public class Logger {
    private static final Logger INSTANCE = new Logger();

    private Logger() {
        // do something to initialize the logger
    }

    public static Logger getInstance() {
        return INSTANCE;
    }

    // implementation ...
}

Then any code which needs to reference the logger doesn't need to instantiate it (can't, in fact), and instead just uses the singleton:

Logger.getInstance().Log("some message");

Other real-world examples might include a dependency injection container, a read-only data access service (such as a lookup service which caches results), etc. Generally anything where initialization or repeated operations can be heavy and which is thread-safe.

David
  • 208,112
  • 36
  • 198
  • 279
  • he already knows the pattern itself he wanted to know where it is most commonly used. but nice answer. ;) – ChrisKo Aug 11 '15 at 18:11
  • @ChrisKo: Understood, but I figure for completeness I may as well be thorough. – David Aug 11 '15 at 18:12
  • why did you mark that as answer? i answered before him and i didn't provided an code-example since you said you know the pattern – ChrisKo Aug 11 '15 at 18:13
1

Singleton always makes sense when dealing with heavy objects where it makes no sense to have more than one instance across the whole application. Since you are dealing with Web-Applications you should have been dealt with objects which are the same for each user/session/request. Database-Connection-Pool is probably a good example, or a Servlet. It doesn't make sense to create a new Pool for each request. One Pool for the whole application should be sufficient. Other examples are probably Loggers, Email-Client, Global-Settings, those things should be the same instances for each user otherwise you will run out of resources. Or did i get something wrong?

ChrisKo
  • 365
  • 2
  • 8