mardi 12 novembre 2019

How to Structure Model Using Strategy Pattern and Entity Framework

Background

I am building an application for my job using WPF and Entity-Framework. The general idea is that it tracks test results for a chemical company.

Each product has batches and a list of test specifications. Each batch has samples. Each sample has a list of testing results. Each test result is either a normal value or calculated from other test results.

Scenario

For example, a product has

  1. Test 1 is just a value.
  2. Test 2 is just a value.
  3. Test 3 is Test1/Test2 (Test3 could also be something like Test2/99.8).

Each new sample for every batch of this product needs to have a list of results for each of these tests.

  • If I call Test3.Result I would like that result to always be calculated.
  • If I call Test1.Result I would like to always receive the actual result entered.
  • I need to be able to set the value of Test1 and Test2 but not the value of Test3.

My Idea

I have a TestSpec class with a few derived versions. The relevant class is the base class below:

// the base class for all test specifications
public abstract class TestSpec
{
    public TestResultCalculationStrategy Calculator { get; set; }
    public ICollection<TestResult> Results { get; set; }
}


public abstract class TestResultCalculationStrategy
{
    public TestSpec Spec { get; set; }
    public virtual double? Calculate(Sample sample);
}

public class DivisionTestResultCalculationStrategy : TestResultCalculationStrategy
{
    public TestSpec Numerator { get; set; }
    public TestSpec Denominator { get; set; }
    public override double? Calculate(Sample sample)
}


public class TestResult 
{
    public Sample Sample { get; set; }
    public TestSpec Spec { get; set; }
    public double? Result 
    {
        get => Spec.Calculator.Calculate(Sample);
        set => ???
    }
}

My issue is this does not work very well, and when I try to connect it to a view-model for editing a sample it barely works at all.

Does anyone have any better idea?

Aucun commentaire:

Enregistrer un commentaire