This sounds like a job for a Decorator.
Here is the Decorator chapter from "Head First Design Patterns".
What I'm suggesting:
- Make a MyClassDecorator class that is a subclass of your existing MyClass.
- MyClassDecorator should have a field of type of type MyClass that gets set with a reference to an ordinary MyClass object in a constructor.
- MyClassDecorator should override each method to call something() and then the method with the same name in the wrapped object.
That way you can add or not add the "something" functionality based on some value available at runtime:
After that snippet, the rest of the code doesn't need to care whether it's dealing with a basic MyClass object or a basic MyClass object wrapped in a MyClassDecorator. They both implement the same basic MyClass interface.
This is a simplification the standard Decorator
pattern in that...
The pattern is usually used when there is more than one type of additional functionality that might be added.There is usually a separate MyClassDecorator class between MyClass and the various decorators. Since there was only one decorator in this case, I decided to not bother with the extra overhead of the additional intermediate Decorator class.
I hope this helps.
Ryan