Apr 4, 2009

Design Patterns: Creational - Singleton

Singleton Pattern:
  • a class manages the creation of its one and only instance through a static variable
  • no Public constructors, constructors are declared as Private
  • a Singleton object is not instantiated using the new() operator but calling a static method to request for an instance
  • may implement "lazy instantiation", if an instance is not needed then it doesn't get created
  • "eager instantiation" may be implemented if the overhead of creation and the runtime aspects of the Singleton is not burdensome
  • Singletons are meant to be used sparingly
Lazy Instantiation:

in Java:
public class Singleton {
private static Singleton uniqueInstance;

private Singleton() {}

public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}


Eager Instantiation:

in C#:
public sealed class Singleton
{
static readonly Singleton uniqueInstance = new Singleton();

Singleton() {}

public static Singleton getInstance {
get { return uniqueInstance; }
}
}

in Java:
public class Singleton {
private static Singleton uniqueInstance = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return uniqueInstance;
}
}

No comments:

Post a Comment