构造函数可以中止实例化吗? [英] Can the constructor abort instantiation?
本文介绍了构造函数可以中止实例化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在构造函数中进行测试,以找出使用给定参数实例化对象当前是否是一个好主意。但是,我该如何终止并从构造函数向新语句返回警告?必须在每个新语句之前由调用方进行这样的测试吗?我认为构造函数将是一个理想的选择。
I want to make tests in a constructor to find out if it is currently a good idea to instantiate the object or not, with the given parameters. But how could I abort and return a warning from a constructor to the new statement? Must such tests instead be done by the caller before each "new" statement? I thought that the constructor would be a good place for it.
推荐答案
您可以使用工厂对象代替。然后可以运行检查并返回实例化的对象,或者返回null。这可能比例外更为有效。
You could use a factory object instead. This could then run your checks and return the instansiated object, or null. This would probably be more efficient than an exception.
MyObject myObject = MyObjectFactory.createMyObject();
这篇关于构造函数可以中止实例化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文