Saturday 26, Apr 2025
We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 22 July 2017

Design Patterns - Singleton Pattern

Singleton Pattern

Definition

The Singleton pattern provides the possibility to control the number of
instances (mostly one) that are allowed to be made. We also receive a global
point of access to it (them).

Where to use

When only one instance or a specific number of instances of a class are
allowed. Facade objects are often Singletons because only one Facade object
is required.

Benefits

  1. Controlled access to unique instance.
  2. Reduced name space.
  3. Allows refinement of operations and representations.

Drawbacks/consequences

Singleton pattern is also considered an anti-pattern by some people, who feel
that it is overused, introducing unnecessary limitations in situations where a
sole instance of a class is not actually required.

Class Diagram 

Singleton Example

package com.designpattern.singleton;
public class FileLogger {
private static FileLogger logger;
// Prevent clients from using the constructor
private FileLogger() {
}
//Control the accessible (allowed) instances
public static FileLogger getFileLogger() {
if (logger == null) {
logger = new FileLogger();
}
return logger;
}
public synchronized void log(String msg) {
// Write to log file...
}
}

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer

Related Posts:

  • Design Patterns - Chain-of-responsibility Pattern Chain-of-responsibility Pattern The Chain-of-responsibility pattern lets more than one object handle a request without mutual knowledge. We avoid coupling between the sender of a request and the possible receivers. We place… Read More
  • Design Patterns - Abstract Factory Pattern Abstract Factory Pattern Definition The Abstract Factory pattern is a creational pattern which is related to the Factory Method pattern, but it adds another level of abstraction. What this means is that the pattern encapsu… Read More
  • Design Patterns - Decorator Pattern Decorator Pattern Definition The Decorator pattern lets you attach additional responsibilities and modify an instance functionality dynamically. Decorators provide a flexible alternative to subclassing for extending functi… Read More
  • Design Patterns - Singleton Pattern Singleton Pattern Definition The Singleton pattern provides the possibility to control the number of instances (mostly one) that are allowed to be made. We also receive a global point of access to it (them). Where to use … Read More
  • Design Patterns - Composite Pattern Composite Pattern Definition The Composite pattern helps you to create tree structures of objects without the need to force clients to differentiate between branches and leaves regarding usage. The Composite pattern lets c… Read More
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Design Patterns - Singleton Pattern Rating: 5 Reviewed By: eHowToNow