I have X classes with different information and calculation methods that should be shared but could be overwritten, so:
class Rule1 {
int type = 1;
string name = "Rule";
public float Calc()
{
return 1 + 2 + type; // SAME
}
}
class Rule2 {
int type = 2;
string name = "Rule2";
public float Calc()
{
return 1 + 2 + type; // SAME
}
}
class Rule3 {
int type = 3;
string name = "Rule3";
public float Calc()
{
return 3 + 4 + type; // DIFFERENT
}
}
What I want to write in the calling methods are like this:
class Calculator
{
public void Do(List<IRules> ruleList)
{
foreach(var rule in ruleList)
{
rule.Calc();
}
}
}
So how would my interface should have to look like and how to abstract the calc
method as default implementation but overwriteable?
If you have an implementation that's correct for most inheritors but not all, mark it virtual
and override
it in a derived class:
public class BaseCalculation
{
public virtual float Calculate()
{
return 42;
}
}
public class HalfCalculation : BaseCalculation
{
public override float Calculate()
{
return 21;
}
}
You can now use the base class, BaseCalculation
, instead of an interface. If you insist on still using an interface, then you can still define the Calculate()
method in an interface and apply that to your base class:
public interface IRules
{
float Calculate();
}
public class BaseCalculation : IRules
{
// same as above
With the added benefit that you can apply this interface to other classes that also calculate something, but without any of the logic that's in BaseCalculation
.