Create singletone class.
package design.patern.singleton;
public class Singleton {
private static Singleton instance = null;
// Constructor should be private
private Singleton() {
}
// Create instance of class
public static Singleton getInstance() {
if (null == instance) {
instance = new Singleton();
}
return instance;
}
public void demoMethod() {
System.out.println("Print demoMethod");
}
public static void demoStaticMethod() {
System.out.println("Print demoStaticMethod");
}
}
package design.patern.singleton;
public class SingletonMainClass {
public static void main(String args[]){
// Create instance of singleton class
Singleton inst = Singleton.getInstance();
System.out.println(inst.hashCode());
// Call non static methos
inst.demoMethod();
// Call static method
Singleton.demoStaticMethod();
}
}
package design.patern.singleton;
public class Singleton {
private static Singleton instance = null;
// Constructor should be private
private Singleton() {
}
// Create instance of class
public static Singleton getInstance() {
if (null == instance) {
instance = new Singleton();
}
return instance;
}
public void demoMethod() {
System.out.println("Print demoMethod");
}
public static void demoStaticMethod() {
System.out.println("Print demoStaticMethod");
}
}
package design.patern.singleton;
public class SingletonMainClass {
public static void main(String args[]){
// Create instance of singleton class
Singleton inst = Singleton.getInstance();
System.out.println(inst.hashCode());
// Call non static methos
inst.demoMethod();
// Call static method
Singleton.demoStaticMethod();
}
}
If you put output and their explanation, then easy to understand.
ReplyDelete