When a class allows to create only single object, that object is called Singleton Object.
Make the constructor of such class as private constructor.
To send that object to outside world make some static method called as factory method.
import static java.lang.System.*;
class MyClass
{
private static MyClass m=new MyClass(); //Singleton object
private MyClass() {} //private constructor
public void welcome()
{
out.println("Welcome to My Class");
}
public static MyClass getObject() //factory method
{
return m;
}
}
class Hello
{
public static void main(String[] args)
{
MyClass x=MyClass.getObject();
x.welcome();
}
}
Comments
Post a Comment