Singleton Design pattern will allow only one object per Class(JVM).
Before Writing Singleton Design pattern you should follow these steps.
#1). create an instance as static and return type as The same class, and it should be assigned as null.
#2). "Create a Constructor as private" to deny the creation of object from other class.
#3). Write a static method to create object for our class.It should be Once for a class.
#4). At last return the class Object.
Here We are creating the object once only not again and again.The first time created object is returning again when you called.
Before Writing Singleton Design pattern you should follow these steps.
#1). create an instance as static and return type as The same class, and it should be assigned as null.
private
static
Singletonn instance =
null
;
#2). "Create a Constructor as private" to deny the creation of object from other class.
private
Singletonn(){
}
public
static
Singletonn getInstance(){
}
#4). At last return the class Object.
Here We are creating the object once only not again and again.The first time created object is returning again when you called.
package
javabynataraj.basic;
class
Singletonn {
private
static
Singletonn instance =
null
;
private
Singletonn(){
}
public
static
Singletonn getInstance(){
if
(instance==
null
){
instance =
new
Singletonn();
}
return
instance;
}
}
public
class
Singleton{
public
static
void
main(String[] args) {
System.out.println(
"before calling ..."
);
System.out.println(Singletonn.getInstance());
System.out.println(
"Once Called"
);
System.out.println(Singletonn.getInstance());
System.out.println(
"Second time called"
);
}
}
Very informative and worthy post. Thanks for the sharing such a precious updates with us.
ReplyDeleteSamsung - Series 5 Ultrabook 13.3" Touch-Screen Laptop - 4GB Memory - 500GB Hard Drive - Titan Silver
Samsung - ATIV Smart PC Pro 700T Tablet with 128GB Memory - Black