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
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

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