Say you have two interfaces: IPatient
and IOperator
. Each class derived from IOperator
needs to be able to perform a unique operation on an instance of a class derived from of IPatient
. I'll call subclasses of these "Patients" and "Operators" for brevity's sake. Each operation requires access to the Patient
's internal members (whether direct or indirect), and the actual operation may differ depending on which Patient is being operated on.
Consider PatientA
and PatientB
. We have the concept of an operation that makes the patient's internal member become "true", but it must be done differently depending on the patient, as you can see:
class IPatient {};
class PatientA : public IPatient { bool setMeToTrue = false; };
class PatientB : public IPatient { const char* setMeToTrue = "false"; };
Every solution I can think of requires one of the following:
A) Declaring every Operator a friend of Patient
B) Giving Patient
a separate public method for each Operator (teach Patient
to operate on itself, Operator just says "do it")
C) Some solution involving an enum
of every Operator and a big select
statement or similar
The problem with these approaches is that they all require modifying Patient
(or some monolithic enum
) whenever a new Operator is added to the codebase. Also, since each operation is unique to an Operator, having the operation be defined externally to the Operator who performs it feels like a fault in the design. Why even bother having Operators if someone else does all the work?
Is there any way to do this without resorting to the methods listed above?
Aucun commentaire:
Enregistrer un commentaire