I have the following concrete classes that implement a common interface
EvaluatorA : IEvaluator
EvaluatorB : IEvaluator
EvaluatorC : IEvaluator
The interface IEvaluator
has only one function - Evaluate
, which is implemented in all three types of evaluators. And I have a driver class that invokes an evaluator based on configuration, however, it is only having access (by design) to IEvalutor
, i.e., it does not need to know which concrete evaluator is currently being invoked.
The problem arises when one of the evaluators, say EvaluatorC
, needs to implement a new function Predict
, and my requirement is only for EvaluatorC
, the Predict
function needs to be called after calling Evaluate
.
Temporal solution 1: One solution is to check the evaluator type:
// evaluator is previously instanciated
evaluator.Evaluate();
if (evaluator is EvaluatorC)
evaluator.Predict();
As you could see, this is not neat. Say tomorrow I need to call another function Dance
for only EvaluatorB
and function Sing
for both EvaluatorA
and EvaluatorB
, it becomes messy.
Temporal solution 2: Add function Predict
to the interface IEvaluator
, and for other evaluators, just implement the function with an empty body. This could work for void
return type functions, but it needs additional safety check in the driver program if the return type is not void
. In addition, I am not sure if having a function with empty body only as placeholders is a good idea or not.
Temporal solution 3: Change the interface to an abstract class. This is similar to solution 2, but provides a default implementation of Predict
. However, I did not like this approach either as it alters the original structure of the project and does not bring many benefits compared to solution 2.
Overall, I do not have a satisfying solution to this problem. I am hoping that decoration pattern
could help (but I am not sure). This problem is not specific to any programming languages. Please jump in and share your ideas.
Aucun commentaire:
Enregistrer un commentaire