例如,
public class Test {
Test() {
if(xxx)//do some check here
//reject instancing class test.
}
}
我想我可以抛出一个异常来拒绝它,有没有其他办法? 我不确定实例化被拒绝的效果是什么,但我认为一种自然的方式是:
Test test = new Test();//return null here indicating instancing rejected.
我希望 java 和 C++ 都应该具有这种“拒绝”功能。
最佳答案
如果你想返回 null 你可以使用 Factory pattern .例如。您可以编写 Test test = TestFactory.CreateTest();
,而不是 Test test = new Test();
,并在 TestFactory 中实现您需要的所有检查。创建测试
。
new Test()
总是返回一个非空的 Test
实例(至少在 Java 中是这样)。
关于java - "reject"如何实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9305701/