Reputation: 100020
Is there a design pattern (probably but not necessarily OOP) whereby you can implicitly (not explicitly) call one function/method A form all the other methods in an object each time those other methods are called?
for example:
//pseudocode
class Foo {
int count = 0;
void synchronized countUp(){
count++;
}
void doSomethingFirst(){
//call countUp() implicitly here
}
void doSomethingSecond(){
//call countUp() implicitly here
}
}
Would there be a way to use annotations in Java for instance? I could mark methods that need to call super methods or something. So it would be like an implicit call to super. I am not saying this is a great idea I am just wondering if it can be done somehow with a design pattern.
Upvotes: 0
Views: 65
Reputation: 1705
You could probably copy the system (I don't think it is a design pattern) used by the Spring MVC framework. It relies on making the inherited method final, and providing an overloadable method for descendants.
Using part of your example code (in Java):
final void doSomethingFirst(){
countUp();
doSomethingFirstInternal();
}
protected void doSomethingFirstInternal() {
// Empty implementation that descendants can override when necessary.
}
I'm not saying this is a great idea - you need to be 100% sure that your code should execute first. But is an option and careless programmers cannot introduce bugs because they forgot to call super().
Upvotes: 1
Reputation: 434
You could extend the class and overwrite the countUp()
method, after. Make all methods protected and call the superclass methods that you need from the child class.
class Boo extends Foo {
@Override
void countUp() {
setUp();
super.countUp();
tearDown();
}
}
To make this more generic, you could use the observer pattern:
get all its methods at init via reflection
Foo.class.getMethods()
wrap all methods in a class and register as observers
Upvotes: 1