子类计算值的最佳设计模式?
假设我有两种类型:
ClassA
{
int ValueA;
int CalculatedA;
}
ClassB
{
int ValueA;
int CalculatedA;
int ValueB;
int CalculatedB;
}
CalculatedB
需要 ValueA
以及 ValueB
。我正在尝试确定实现此目的的最佳模式。
选项 1:子类 ClassA
并添加额外的值。有一个在子类中重写的通用 Update()
方法。这是模型中的简单代码,但创建这些类的代码需要提前知道要创建哪些类,并且任何迭代这些类型列表的代码都需要进行类型检查以处理额外的字段。
选项 2: 在单独的类中包含额外的属性,并在其中包含 CalculatedB
的更新代码。问题在于,ClassB 需要某种方式来了解 ValueA 何时更新,而我希望不必实现 INotifyPropertyChanged 之类的东西> 关于这些课程。另一种方法是在额外的属性类上使用某种公共 Update 方法,并让主类在更新 ValueA 时调用该方法。亦不可取。
选项 3:只需使用 ClassB
,其中 ValueB
和 CalculatedB
为可为空类型。经过。
还有吗?你会选择哪个?
Say I have two types:
ClassA
{
int ValueA;
int CalculatedA;
}
ClassB
{
int ValueA;
int CalculatedA;
int ValueB;
int CalculatedB;
}
CalculatedB
requires ValueA
as well as ValueB
. I'm trying to decide the best pattern to implement this.
Option 1: Subclass ClassA
and add the extra values. Have a common Update()
method that is overridden in the subclass. This is simple code in the model, but the code to create these classes needs to know which to create in advance, and any code that iterates over a list of these types needs to do type checking to deal with the extra fields.
Option 2: Have the extra properties in a separate class, and have the update code for CalculatedB
there. The issue with this is that ClassB
then needs some way of knowing when ValueA
is updated, and I was hoping to not have to implement something like INotifyPropertyChanged
on these classes. Another way to do this is to have some sort of public Update method on the extra properties class, and have the main class call that method when ValueA
is updated. Also not desirable.
Option 3: Just have ClassB
with ValueB
and CalculatedB
being nullable types. Pass.
Are there any more? Which would you choose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果ClassB与ClassA不相关,那么子类化并不是一个好方法。顺便说一句,在.Net中我们通常不暴露公共字段,而是公开属性(假设C#)
由于ClassB.CalculateB严重依赖ValueA,为什么不直接计算值,这样你就不必担心属性改变。
If ClassB is not related to ClassA, then subclassing is not a good method. BTW, in .Net we normally don't expose public fields, but public properties (assume C#)
Since ClassB.CalculateB is heavily rely on ValueA, why not just calculate the value on the fly, so you don't have to worry about property changing.