Singleton :
A singleton class is one which allows us to create only one object for JVM.
we can use it to create a connection pool.
class Stest {
private static Stest st; // private variable
private Stest() { // private constructor
System.out.println("OBJECT CREATED FIRST TIME");
}
public static Stest create() //Factory method
{
if (st == null)
{
st = new Stest();
} else
{
System.out.println("OBJECT ALREADY CREATED");
}
return st;
}
public static void main(String[] args) {
Stest st1 = Stest.create();
Stest st2 = Stest.create();
Stest st3 = Stest.create();
if ((st1 == st2) && (st2 == st3) && (st3 == st1)) {
System.out.println("ALL OBJECTS ARE SAME");
} else {
System.out.println("ALL OBJECTS ARE NOT SAME");
}
}
}
OUTPUT :
OBJECT CREATED FIRST TIME
OBJECT ALREADY CREATED
OBJECT ALREADY CREATED
ALL OBJECTS ARE SAME
A singleton class is one which allows us to create only one object for JVM.
we can use it to create a connection pool.
class Stest {
private static Stest st; // private variable
private Stest() { // private constructor
System.out.println("OBJECT CREATED FIRST TIME");
}
public static Stest create() //Factory method
{
if (st == null)
{
st = new Stest();
} else
{
System.out.println("OBJECT ALREADY CREATED");
}
return st;
}
public static void main(String[] args) {
Stest st1 = Stest.create();
Stest st2 = Stest.create();
Stest st3 = Stest.create();
if ((st1 == st2) && (st2 == st3) && (st3 == st1)) {
System.out.println("ALL OBJECTS ARE SAME");
} else {
System.out.println("ALL OBJECTS ARE NOT SAME");
}
}
}
OUTPUT :
OBJECT CREATED FIRST TIME
OBJECT ALREADY CREATED
OBJECT ALREADY CREATED
ALL OBJECTS ARE SAME
No comments:
Post a Comment