For example,
public class Test {
Test() {
if(xxx)//do some check here
//reject instancing class test.
}
}
I think I can throw a exception to reject it, is there any other way?
I am not sure what’s the effect of instancing been rejected, but I think a natural way is:
Test test = new Test();//return null here indicating instancing rejected.
I expect java and C++ all should have this “reject” feature.
There is no such feature built into the language, but you have two standard ways of implementing it:
Choosing between the two options is not easy. The guideline is that if rejecting instantiation is an exceptional situation, e.g. a programming or a configuration error, then go the exception route. If rejections are going to happen routinely, e.g. because some resource is temporarily unavailable, then go the factory method route. Of course there are exceptions to these rules, so use your best judgement.