I have the following code where the goal is that when a method is called on a parent it then calls the same method on all of it's children, this is then where the actual work is done.
public class Parent {
Child[] children;
public doWork() {
for(int i = 0; i < children.size(); i++) //For all my children
children.get(i).dowork(); //Call the same method
Log.ReportWorkBeingDone(this); //Report this has happened
}
}
public class Child extends Parent{
@override
public doWork() {
//Actual Work //Run the actual code
Log.ReportWorkBeingDone(this); //Report this has happened
}
}
Right now when the doWork()
is called on the parent the Log
class gets a method call from the Parent
and then once from each of the Child
objects in it's array.
Is there a programming pattern or just a good way of only running the call to the Log
class once? So if doWork()
is called on a Child from outside this chain of classes then the child will call the Log
method but if doWork()
is called on the parent only the parent will call the Log
method and the children won't?
All I can think of is having something like this:
public class Parent {
Child[] children;
public doWork() {
sneakyHiddenWork();
Log.ReportWorkBeingDone(this); //Report this has happened
}
protected sneakyHiddenWork(){
for(int i = 0; i < children.size(); i++) //For all my children
children.get(i).sneakyHiddenWork(); //Call the same method
}
}
public class Child extends Parent{
@override
protected sneakyHiddenWork() {
//Actual Work //Run the actual code
}
}