Singleton Class in Java with example
Singleton
Class in Java:
A class
said to be singleton class, when we are able to create only one object for a
class
To create
a singleton class, the class should contain a private constructor and a factory
method
Factory Method:
if a method provide an object of its own class then it is called factory method
and Factory method should be declared as static
Example
:
Class
Test{
Static
sample s1;
Private Test(){ }
Void
msgMethod(){
System.out.println(“”good
morning friends”);
}
Static
Test getObject(){
If
(s1==null)
s1=new Test();
return
s1;
}
Class
Demo {
public
static void main(String args[]){
Test t=Test.getObject();
t.msgMethod();
}
}
0 Comments