I have a concrete class A like
class A{
doStuff() {
// do some stuff
}
}
and a derived class B that extends it
class B extends A {
doStuff(){
super.doStuff();
// do some other stuff proper to B
}
}
Up until here I'm satisfied with inheritance, but now I'm in need to extend both A
and B
with some extra functionality, that (if I still use inheritance) will end up looking sort of like
class APlus extends A {
doStuff(){
super.doStuff();
// do Plus-stuffs
}
}
class BPlus extends B {
doStuff(){
super.doStuff();
// do Plus-stuffs
}
}
which is essentially duplicating code, so a no-go.
The first way that comes to mind to solve this is to use composition, like
class Plus {
private A memberOfTypeAorB;
doStuff(){
memberOfTypeAorB.doStuff();
// do Plus-stuffs
}
}
but this is sort of weird because I'd need a lot or changes to accomodate the initialization of memberOfTypeAorB
and in terms of domain/businees APlus
and BPlus
ARE a subtype of A and I have scattered around a lot of functions like
compute(A)
that we'd need to modify now to accept also Plus
es ...
The other way is of course also possible, using composition to add the Plus
functionality to both A
and B
, like a strategy-pattern of sort, but I find it awkward since the default strategy in the majority of the cases is "don't do Plus
stuffs" ... but maybe it's not awkward, actually now that I've written this down I find this solution more appealing!
I have about zero knowledge about design-patterns but hopefully this is not a new problem so ... Does anyone have a better idea?
Aucun commentaire:
Enregistrer un commentaire