What is singleton design pattern? If we declare a contructor as private scope, how can instantiate the class,
class A{
private void A(){
}
..
}
class MainClas{
A aObj=new A();
// Is this line possible ?
Why we go for these kind of design ?
Plz help
Printable View
What is singleton design pattern? If we declare a contructor as private scope, how can instantiate the class,
class A{
private void A(){
}
..
}
class MainClas{
A aObj=new A();
// Is this line possible ?
Why we go for these kind of design ?
Plz help
This will not be considered as a constructor of class A, coz there is never a return type declared for a constructor.
This would be treated as one of the methods of class A.
For instantiating these types of classes you will have to define a public static method, which should call the private constructor (if not called earlier) and return the object of type A.
No this line is not possible if you declare your constructor to be private in the class.Quote:
class MainClas{
A aObj=new A();
// Is this line possible ?
This kind of design is necessary when you want your application resources to be initialized only once. Infact, there can be n number of reasons for this.Quote:
Why we go for these kind of design ?
Plz help
The purpose of a singleton is to reuse some scarce resource. For example, a process only gets one standard out pipe. To share this across multiple scopes, a singleton is used. In Java, that singleton is System.out.
If the constructor is private, then the singleton instance must be created statically somehow. Some singletons have static blocks to create the singleton when the class gets loaded, and others have a lazy creation scheme that only creates the singleton when a program first requests access to it.
Statically loaded example:
...or the lazy style initializationCode:
public class A {
private static A singleton = null;
static {
singleton = new A();
}
private A() {}
public static A getSingleton() {
return singleton;
}
}
Code:public class A {
private static A singleton = null;
private A() {}
public synchronized static A getSingleton() {
if(singleton == null)
singleton = new A();
return singleton;
}
}