Consider the following scenario: I have a class A composed of various parts Part 1, Part 2, etc., and I want to extend the functionality of A by subclassing.
The issue: if I tried to override the behaviour of the individual "Parts" (is there a better term?) the same way, I would have to create one subclass for each Part that changes, which gets messy and confusing quickly.
In a nutshell: I want to override class methods without resorting to subclassing.
I thought of a solution, but I'm unsure if it is a good idea:
Suppose I want to override Part::Method. Instead of using the inheritance mechanism provided by my language, I could "fake" an overriding capability by:
- passing the
Partclass a functionMethodOverride(e.g. as an anonymous function), and - having
Part::MethodcallMethodOverride
I can see two downsides to that approach:
- it ignores the (perfectly capable but impractical) inheritance feature of the language, which may have unforeseen side-effects
- access non-public members of
Partbecomes a hassle
My question(s): Is there an established design pattern that solves the described issue in a similar (or better) way? Are there any downsides I missed?
Aucun commentaire:
Enregistrer un commentaire