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 <-----");
}
}
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