Andy Brandi
Andy Brandi

Reputation: 195

Looking for design pattern: Method overriding without subclassing

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:

I can see two downsides to that approach:

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?

Upvotes: 1

Views: 2473

Answers (1)

Pumphouse
Pumphouse

Reputation: 2053

When you want to avoid subclassing but still require the ability to provide a set of classes related algorithms, you're usually looking at the visitor pattern.

Each class will compose a visitor object, and call one of it's functions. This eliminates the need to subclass multiple objects just to get a method.

Visitor Pattern Example

Like mentioned above your example of passing in a method override is very similar to the strategy pattern, but according to your post...

I would have to create one subclass for each Part that changes

I'm assuming the point is to avoid creating multiple classes, only to provide limited functionality. Both your method override example and the strategy pattern require a class for each different override/strategy (algorithm).

Strategy Pattern Example

The visitor only adds one class, and keeps all the logic in the visitor class. No need to subclass multiple times, just add a new algorithm into the visitors concrete implementation.

Upvotes: 1

Related Questions