Skip to content

Instantly share code, notes, and snippets.

@biniama
Last active October 20, 2018 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biniama/25ecab66bfd9484ff417a75bb8d7c9fc to your computer and use it in GitHub Desktop.
Save biniama/25ecab66bfd9484ff417a75bb8d7c9fc to your computer and use it in GitHub Desktop.
Singleton Pattern - Multiple Implementations by Allen Holub (holub.com/patterns)
class Singelton {
static Singleton instance = null;
//private constructor
private Singelton() {}
public static Singleton getInstance() {
if(instance == null)
instance = new Singleton();
return instance;
}
}
class Singelton {
private class InstanceContainer {
private static final Singleton theInstance = new Singelton();
}
// you are free to define and access static variables without issue since the instance will only be defined in the inner class.
static int MAX = 10;
public static Singleton getInstance() {
return InstanceContainer.theInstance;
}
}
Singleton Pattern should be:
* globally accessible
* there should only be one and only instance of that class
-> Can also be a class where all methods are static (like Utitlity class)
//Using Java's Synchronized keyword for handling issue in MultiThreading
class Singelton {
private static Singleton instance = null;
//above line can also be defined as
//private static Singleton instance; // null by default
//private constructor
private Singelton() {}
public synchronized static Singleton getInstance() {
if(instance == null)
instance = new Singleton();
return instance;
}
}
//Using a custom Lock class for handling issue in MultiThreading
class Singelton {
Lock busy;
static Singleton instance = null;
//private constructor
private Singelton() {}
public static Singleton getInstance() {
busy.lock();
if(instance == null)
instance = new Singleton();
return instance;
busy.unlock();
}
}
//Initialize first to avoid issues in the if statement
class Singelton {
private static Singleton instance = new Singelton();
//private constructor
private Singelton() {}
public synchronized static Singleton getInstance() {
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment