子类计算值的最佳设计模式?

发布于 2024-10-16 19:46:08 字数 806 浏览 2 评论 0原文

假设我有两种类型:

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,其中 ValueBCalculatedB 为可为空类型。经过。

还有吗?你会选择哪个?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哽咽笑 2024-10-23 19:46:08

如果ClassB与ClassA不相关,那么子类化并不是一个好方法。顺便说一句,在.Net中我们通常不暴露公共字段,而是公开属性(假设C#)

public class ClassA{
    public int ValueA {get;set;}
    //...
}

由于ClassB.CalculateB严重依赖ValueA,为什么不直接计算值,这样你就不必担心属性改变。

public class ClassB {
    public int ValueB {get;set;}
    public int getCalculateB(ClassA a){
        //...
    }
}

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#)

public class ClassA{
    public int ValueA {get;set;}
    //...
}

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.

public class ClassB {
    public int ValueB {get;set;}
    public int getCalculateB(ClassA a){
        //...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文