开发者

Best design pattern for calculated values on a subclass?

开发者 https://www.devze.com 2023-02-09 16:02 出处:网络
Say I have two types: ClassA { int ValueA; int CalculatedA; } ClassB { int ValueA; int CalculatedA; int ValueB;

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 t开发者_如何学编程o 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?


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){
        //...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号