Hello!
I have two classes (A and B) which depend on each other in following sense:
Each class has a method performing some action.
The action of each class depends on an action of the other class.
So, if the user calls action of class A, it should automatically call
action of class B.
Same for the other way. But an infinite loop should be prevented.
I have found some code, which deals with this issue, but it seems to be a little dumb to me: Infinite loop is prevented by locking.
import java.util.concurrent.locks.*;
import static java.lang.System.*;
import org.junit.*;
public class TEST_DependentActions {
static class A {
private B b = null;
private final ReentrantLock actionOnBLock = new ReentrantLock();
public void setB(B b) {
this.b = b;
}
public void actionOnB() {
if (!actionOnBLock.isLocked()) {
actionOnBLock.lock();
b.actionOnA();
actionOnBLock.unlock();
}
}
}
static class B {
private A a = null;
private final ReentrantLock actionOnALock = new ReentrantLock();
public void setA(A a) {
this.a = a;
}
public void actionOnA() {
if (!actionOnALock.isLocked()) {
actionOnALock.lock();
a.actionOnB();
actionOnALock.unlock();
}
}
}
@Test
public void test1()
throws Exception {
out.println("acting on class A first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
a.actionOnB();
}
@Test
public void test2()
throws Exception {
out.println("acting on class B first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
b.actionOnA();
}
}
Output is as following:
acting on class A first:
A : calling class B's action.
B : calling class A's action.
acting on class B first:
B : calling class A's action.
A : calling class B's action.
Well, it works, but doesn't seem to be an optimal solution.
How would you do it?
Is there a pattern which deal with such issue?
EDIT:
I want to know it in general.
But let's say I have a Container which contains multiple Elements.
The Container provides the method remove(someElement) and the
Element also provides a method removeMe().
Both methods depend on each other, but can't be connected to one
method, because both methods additionally perform some internal stuff, which is only
accessible inside each class.