I need to create math problems. Arithmetic, Comparison 2 numbers.. every class contains similiar features like CheckTheAnswer and GenerateProblem, but each one of them receives different parameters. Here is an example what I’m trying to do.
public class Problem<T>
{
public virtual bool CheckTheAnswer()
{
return false;
}
public static T GenerateProblem()
{
return T;
}
}
public class Arithmetic : Problem<Arithmetic>
{
public bool CheckTheAnswer(decimal result)
{
...
}
public static Arithmetic GenerateProblem(Tuple<int, decimal, decimal> condition)
{
...
}
}
public class Comparison2Numbers : Problem<Comparison2Numbers>
{
public bool CheckTheAnswer(decimal result1, decimal result2)
{
...
}
public static Comparison2Numbers GenerateProblem(Tuple<decimal, decimal> condition)
{
...
}
}
I was thinking in interfaces, but I realized in interfaces can’t have static functions.
Thanks in advance.
OK, the question is.. is there a way to do this?
Arithmetic a = new Arithmetic();
Problem<Arithmetic> p = a;
And get the functions from Arithmetic class. Maybe this is not the best way to generalize this problems, what do you opine?
To get the behavior of polymorphic creation, the abstract factor pattern would be best for this. See Mark’s answer for an example of how to set this up.
But you also need the ability to check the answer with different number of arguments. From your examples, it seem that you will always expect a type of
decimalfor each of the arguments. Assuming this is correct, you can makeCheckTheAnswera variadic method. I might also suggest adding a polymorphic property to access the desired number of arguments. So we now have:And the a base class could be along the lines of:
While this doesn’t provide compile-time type safety in the number of arguments, it will allow you to solve your problem using run-time guarantees.