You would use a Static Factory
public class Test{
private Test() {
//Prevent construction by other classes, forcing the
// use of the factory
}
public static Test create(){
return new Test();
}
public static void main (String[] args){
Test ob = Test.create();
}
}
I’ve made a few changes to your example to show that this way an instance can only be obtained via the factory. This gives you control over how (and how many) instances are created.
For instance, you can also make it such that the factory always returns the same instance (a singleton)
private static Test instance;
public static Test create(){
synchronized (Test.class) {
if(instance == null)
instance = new Test();
}
return instance;
}
This way the class Test
would only get created a single time.
There are many other variations you can build into your factory method based on your specific requirements.
6
solved How to return current object by static method?