Solving a specific design question using generics: correct in this case?
Let's say I have an interface IAutoTask
and few other classes implementing that interface, RegularTextAnswerTask
, SelectAnswerTask
, JoinPairsTask
etc. Each of these classes defines an EvaluateAnswer
method returning an int - but the parameter for the method differs.
public sealed class SelectAnswerTask : IAutoTask
{
public int EvaluateAnswer(int[] answer);
}
public sealed class RegularTextAnswerTask : IAutoTask
{
public int EvaluateAnswer(string 开发者_StackOverflow中文版answer);
}
public sealed class JoinPairsTask : IAutoTask
{
public int EvaluateAnswer(int[,] answer);
}
Now, what should the definition of the interface look like? I came up with:
public interface IAutoTask<AnswerType>
{
int EvaluateAnswer(AnswerType answer);
}
And modifying the implementors as follows:
public sealed class SelectAnswerTask : IAutoTask<int[]>
{
public void EvaluateAnswer(int[] answer)
{
}
}
etc.
Do you consider this approach to be a correct one?
Your approach is acceptable, although the best design choice also depends on the way you expect the consumers of your class (i.e. those that use _____AnswerTask
) to use it.
Naming conventions for Generic Type Parameters suggest a slight modification to your interface definition:
public interface IAutoTask<TAnswer>
{
int EvaluateAnswer(TAnswer answer);
}
精彩评论