Wednesday, September 24, 2014

Java Singleton Design Pattern

Info
given ways to create Singleton design pattern class
1) Using private constructor  and a getter method for an Instance
2) Using private constructor and public static final Instance of a Class

package com.raj.dp;
class Universal {

private Universal(){
universe =  this;
}

public void printMessages(){
System.out.println("Good morning. Have a beautiful day.");
}

public static Universal getUniverse(){
return universe;
}

public static void initialize(){
universe = new Universal();
}

public String toString(){
return "Hello friend.\nMy name is Universal and i m a Singleton Factory pattern class.";
}

public static Universal universe;
}

//Singleton with public final field
class Earth {
public static final Earth INSTANCE = new Earth();
private Earth() { 

}
public void makeMyEarthGreen() { 
System.out.println("Hello ");
}
}

class SingletonEngine{

public static void main(String rk[]){
System.out.println("----->Start<-----\n");
Universal.initialize();
Universal universe = Universal.getUniverse();
System.out.println("Universe : "+universe);

universe.printMessages();
Earth.INSTANCE.makeMyEarthGreen();
System.out.println("\n-----> End <-----");
}

}

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...