AsI have the feeling that you said,absolutly want to use a pattern. Be warned that using the decoratora design pattern isdoesn't always result in a good solutionbetter code ! Remember that design patterns must serve the developper and not the opposite.
Here's a canvasYour case is tricky as it seems you want to do 2 kinds of howlogging:
- Logging some steps of your logical functionality (inside
execute)
- Logging around function calls (entering/exiting a function) (outside
execute)
For the first case, at the moment you want to log some things inside a function, you have to do it... inside the function. You could be implemented:use the template method pattern to make things a bit prettier but I think it's overkill in this case.
public final class MyFunctionMyBusinessFunction extends AFunctionBaseFunction {
@Override
public final void execute() {
//dolog.info("Initializing thesome realvariables");
computation here int i = 0;
double d = 1.0;
log.info("Starting algorithm");
for(...) {
...
log.info("One step forward");
...
}
log.info("Ending algorithm");
...
log.info("Cleaning some mess");
...
}
}
For the second case, the decorator pattern is the way to go:
public final class MyLoggedFunctionLoggingFunction extends AFunctionBaseFunction {
private final AFunctionBaseFunction origin;
public MyLoggedFunctionLoggingFunction(AFunctionBaseFunction origin) {
this.origin = origin;
}
@Override
public final void execute() {
//log before.info("Entering functionexecute");
origin.execute(); //real call to the function
//log after.info("Exiting functionexecute");
}
}
Usage ifAnd you only want to perform the executecould use it like this in BusinessClass:
AFunctionpublic final BusinessClass {
private final BaseFunction f1;
public BusinessClass() {
this.f1 = new MyFunctionLoggingFunction(new MyBusinessFunction());
}
public final void doFunction() {
f1.execute();
}
}
Usage if you also want the start/end of the functionA call to be loggeddoFunction will log this:
AFunctionEntering f1function
Initializing =some newvariables
Starting MyLoggedFunction(newalgorithm
One MyFunction());step forward
f1One step forward
.execute();..
Ending algorithm
Cleaning some mess
Exiting function