OOP:在这种情况下,正确的类设计应该是什么?
我有一个来自 GUI 的对象 guiObject
。根据其数据字段,我需要实例化适当类的 domainObject
。它可以是 DomainClassA
或 DomainClassB
。
DomainClassA
有一个整数构造函数参数 intParamA
(来自 guiObject.fieldA
)。
DomainClassB
有一个整数构造函数参数 intParamB
(来自 guiObject.fieldB
)。
为了解决这个问题,我制作了 AbstractFactory
,它从 guiObject
中获取所需字段,并使用适当的字段实例化 DomainClassAFactory
或 DomainClassBFactory
来自 GuiClass
并重新调整它。反过来,这些工厂 create()
中的任何一个都会正确实例化 domainObject
。
但现在,根据 guiObject.fieldC
,我需要在实例化 domainObject
之前更改 intParamA
和 intParamB
(即减少 1)代码>.为了实现这一目标,我必须为每个 DomainClass 的每种不同类型的“参数更改”创建单独的工厂,然后创建单独的抽象工厂来生成正确的工厂。听起来很丑,看起来也很丑。
正确的设计应该是怎样的?
I have an object guiObject
that comes from GUI. Based on its data fields I need to instantiate domainObject
of proper class. It can either be DomainClassA
or DomainClassB
.
DomainClassA
has one Integer contructor parameter intParamA
(comes from guiObject.fieldA
).
DomainClassB
has one Integer contructor parameter intParamB
(comes from guiObject.fieldB
).
To solve this problem I made AbstractFactory
that takes required fields from guiObject
, instantiates either DomainClassAFactory
or DomainClassBFactory
with proper fields from GuiClass
and retuns it. In turn, either of those factories create()
properly instantiated domainObject
.
But now, depending on guiObject.fieldC
I need to alter intParamA
and intParamB
(i.e. decrease by 1) before instantiating domainObject
. To achieve that I had to create separate factories for each different type of "parameter altering" for each DomainClass
and then create separate abstract factories that produce correct factories. That sounds ugly and that looks ugly.
What should be the correct design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非您需要所有这些层,否则请拥有一个询问
guiObject
并返回正确类型的工厂。过度分析会导致产生太多大多数应用程序根本不需要的东西。仅当绝对必要时才添加额外的抽象层。他们通常不是。
Unless you need all those layers, have a factory that interrogates the
guiObject
and returns the right type.Over-analyzing leads to way too much stuff that most apps simply don't need. Add additional layers of abstraction only if they're strictly necessary. They're usually not.
我个人会将所有这些逻辑放在原始工厂中,而不是试图将其分散得太多:
I'd personally put all this logic in the original factory rather than trying to spread it out so much: