在设计类和它们之间的“通信”时,我总是尝试以这样一种方式设计它们,即所有对象构造和组合都在对象构造函数中进行。我不喜欢从外部进行对象构造和组合的想法,就像其他对象在我的对象上设置属性和调用方法来初始化它一样。当多个对象尝试对您的对象执行此操作并且您永远不知道您的 props\methods 将以什么顺序执行时,这尤其难看。
不幸的是,我经常遇到这种情况,尤其是现在随着依赖注入(inject)框架的日益流行,许多库和框架都依赖于某种外部对象初始化,而且经常不仅需要在我们的对象上注入(inject)构造函数,还需要在属性上注入(inject)构造函数注入(inject)也是。
我的问题是:
让依赖于某些方法或属性的对象在调用它们之后可以认为它们已初始化是否可以?
当您的对象充当接收者并且必须支持调用它的多个接口(interface)并且这些调用的顺序很重要时,是否存在某种模式? (比设置标志更好的东西,比如 ThisWasDone、ThatWasCalled)
最佳答案
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
没有。 Init 方法很痛苦,因为无法保证它们会被调用。一个简单的解决方案是切换到接口(interface)并使用工厂或构建器模式来组合实现。
@Mark Seemann 写了一篇关于它的文章:http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx
Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
builder 模式。
关于C# 对象在构造函数外构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7578761/