Reputation: 5242
I came cross a class with private constructor but the object is returned by another public method by call to the private constructor. What may be the advantage of such a construct when we could have made the constructor public?
public final class TokenTable {
static public int errorToken = 0;
static public int timesToken = 1;
static public int divToken = 2;
static public int plusToken = 11;
......
......
private final HashMap<String, Integer> keywordMap = new HashMap();
private final HashMap<String, Integer> operationMap = new HashMap();
private TokenTable() {
operationMap.put("*", timesToken);
operationMap.put("/", divToken);
operationMap.put("+", plusToken);
....
}
static public TokenTable getInstance() {
LexTokenTabInstance = new TokenTable();
return LexTokenTabInstance;
}
}
Upvotes: 0
Views: 3618
Reputation: 12754
If you do not want to protect creation of multiple instance outside the class then you can create private constructor.
This is helpful creating a single instance.
You can do it like(Eager loading):
private static final TokenTable tokenTable = new TokenTable();
static public TokenTable getInstance() {
return tokenTable;
}
Or, you can do it like(Lazy loading):
private static TokenTable tokenTable;
static public TokenTable getInstance() {
if(null == tokenTable){
tokenTable = new TokenTable();
}
return tokenTable;
}
Upvotes: 0
Reputation: 32969
This is called the Factory
pattern. Check out the description here - Factory Design Pattern.
There are several advantages:
new
<>
operatorTo be clear, the above example it seems that it was done just as a "good practice" since none of the above capabilities was used (other than you don't have to use "new").
Upvotes: 6
Reputation: 692181
This is called a factory method. A factory method has many advantages over a constructor:
Upvotes: 3
Reputation: 5761
The primary reason for hiding a constructor of a class is to control how objects of that class are created. A common example of this is in the Singleton pattern, where only one object of a class is instantiated.
In order to police this, the user accesses a static method which will access the private constructor if the object isn't created, or else return a reference to the already created object:
public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo.class){
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
For other examples, look at Factory patterns in general: http://en.wikipedia.org/wiki/Factory_method_pattern
Upvotes: 0
Reputation: 19304
The main advantage is that no one can create an instance, but using static getInstance
method.
This way you can make sure only one instance is created, just as Singelton design pattern
Upvotes: 0