Creating instance in java class
Please advise me the difference between two ways of declaration of java constructor
public class A{
private static A instance = new A();
public static A getInstance() { return instance;
}
开发者_运维知识库 public static void main(String[] args) {
A a= A.getInstance();
}
}
AND
public class B{
public B(){};
public static void main(String[] args) {
B b= new B();
}
}
Thanks
- Class
A
is supposed to be a Singleton, where you can only have one instance of A. You retrieve that single instance by callinggetInstance();
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
There are a few ways to go about this depending on your requirements:
public class A{
private static A instance = new A();
private A(){} // private constructor
public static A getInstance() {return instance;}
}
or not creating the instance until the first call
public class A{
private static A instance = null;
private A(){} // private constructor
public static A getInstance() {
if(instance == null){
instance = new A(); // create the one instance.
}
return instance;
}
}
- Class
B
is a class with a no-parameter constructor. You can create as many B instances as you want by callingnew B();
It looks like A is an attempt at implementing the singleton pattern, but it's not quite right - it should have a private constructor:
class A {
private static final A INSTANCE = new A();
private A() { }
public static A getInstance() { return INSTANCE; }
}
This ensures that only one instance of A ever exists in your application - if any other object needs to use an instance of A to do something, the only way it can get one is via the getInstance()
method, which returns the same instance all the time.
With B, you can have as many instances of B as needed/desired, and any other object is free to make a new instance of B if it chooses.
In the first case, only one instance available. In the second case, one can have as many as possible. You need to make the constructor private in the in the first case.
精彩评论