工厂对象由于依赖于自身而导致 stackoverflowException
我有 ac# 工厂对象,它使用对象列表作为源,通过工厂方法创建对象。
对象列表的创建方式如下:
public WidgetFactory()
{
widgetLibrary = new List<WidgetModel>();
//Add all widgets
widgetLibrary.Add(new ClientsWidget());
widgetLibrary.Add(new InstallationsWidget());
etc.
我的应用程序的各个部分以不同的方式访问该列表以获取它所需的对象类型。
但我现在有一个要求,列表中的对象之一(即小部件)需要使用小部件工厂本身。显然这会导致循环引用。
我怎样才能改变我的设计来满足这种需求?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,对象不应该依赖于创建它们进行构造的工厂,因为它正是导致这个问题的原因。如果您可以推入对工厂的引用,但在需要时才使用它,则可能会解决问题。
如果您确实需要这样做,那么最好的方法可能是在工厂内延迟实例化对象。您可以使用
List>
,而不是让WidgetFactory
在内部包含List
。这将允许单个“小部件”仅根据需要进行评估,这意味着,当相关小部件尝试引用工厂时,它将被完全加载。Typically, objects should not rely on the factory that creates them for construction, as it causes exactly this problem. If you can push in the reference to the factory, but not use it until it's needed, it may solve the issue.
If you absolutely need to do this, then the best approach may be to lazily instantiate the objects within the factory. Instead of having your
WidgetFactory
contain aList<WidgetModel>
internally, you could use aList<Lazy<WidgetModel>>
. This would allow the individual "widgets" to only evaluate as needed, which would mean that, when the widget in question tries to reference the factory, it'll be fully loaded.你的模型是错误的。一旦汽车离开 NUMMI 工厂的装配线,它就不再依赖于工厂的正常运行。
另外,我对你们工厂的设计提出质疑。为什么你要
new
实例构造函数。那服务的目的是什么?您可能应该告诉我们更多有关您的模型以及您认为需要此模型的原因。如果做得好的话,很可能你不会。
Your model is wrong. Once a car has left the assembly line at the NUMMI plant, it doesn't depend on the plant to operate properly.
Also, I question the design of your factory. Why are you
new
instances the constructor. What purpose is that serving?You should probably tell us a little bit more about your model and why you think you need this. Odds are, properly done, you don't.
WidgetFactory 的构造函数不应该调用它正在构建的事物的构造函数。相反,WidgetFactory 应该有一个方法 (
BuildWidgets
) 来完成所有工作。然后其他对象可以使用工厂,而不会导致这一级联活动重新开始。
The constructor for the WidgetFactory should not be calling the constructers of the things that it is building. Instead, the WidgetFactory should have a method (
BuildWidgets
) that does all of the work.Then the other objects can make some use of the factory without causing this cascade of activity to start over again.
对于初学者来说,将 Widget 创建移出 WidgetFactory 的构造函数。这应该发生在初始化方法中或按需发生在 CreateWidget(Type) 方法中。
要使工厂实例可供 Widget 实例使用,您可以执行以下几种不同的操作之一:
For starters, move Widget creation out of the WidgetFactory's constructor. This should happen either in an initialization method or on-demand in a CreateWidget(Type) method.
To make the factory instance available to the Widget instances, you can do one of a few different things: