007.
mySingletonInstance = new MySingleton (); //
create the object only if it is null
}
return mySingletonInstance;
}
public void doSomething () {
System.out.println(“I am here....”);
}
public static void main(String a[]) {
MySingleton mySingleton =
MySingleton.getInstance();
mySingleton.doSomething();
}
}
Here, a private constructor and a
public getInstance method is
defined. The getInstance checks if an instance exists. If an
instance does not exist, it creates
one using the private
constructor. If an instance exists, it just returns it.
Any external
class that needs an instance of the Singleton class, needs to
obtain it via the getInstance method. The getInstance
method ensures that there is only one
instance of the Singleton
class.
Do'stlaringiz bilan baham: