Lets say we have an object (A), which should execute a method of another object (B) which is not in the scope of the object (A) itself, nor it is in the scope of its members.
The overcome this problem I might one of the following methods:
-
Store a reference to the object with in any object that might use it, might led to a memory leak
-
Create getters for any object that I might need to use and use them like that (which is probably not the best practice).
anObject.getABC().getDEF().getHIG().DoSomething(); -
Define some of the object as a single tone, this might be a good solution but whenever I use a libery overrding it might be a pain, its subclasses wont work with the over ridden one.
-
static members, probably the worst way.
My question: What is the best way to do it, and what should be taken into consideration, while maintain object oriented code?
(The questions refers to general OOP, however I prefer code examples in JAVA)
Examples:
-
users clicks something on the menu this should affect something that is not related to the menu nor anything closely related to it.for
-
A class that has a consume method which should free its memory should access objects that might hold is reference but not directly related to it.For instance, there is a car object which is drawn on a canvas should delete itself from it and from array that hold a list of cars that doesn’t have any relational to the GUI thread.
The Law of Demeter says: Don’t talk to strangers.
If A needs to call a method of B, then B should be a direct dependency of A. If B is in fact not a direct dependency of A, but is a transitive dependency, i.e. A depends on C, which depends on D, which depends on B, then A should call a method of C, which would call a method of D, which would call the method of B:
Reading your examples, it looks like you’re looking for the Observable/Observer method. For example: when you click on a menu, the menu should just call a method of its observers (or listeners, in Swing/AWT terminology), which are instances of an interface. The listener would register itself to the menu, in order to be notified of a menu click.