I'm new to Java, and while reading documentation so far I can't find any good ways for programming with loose coupling between objects. For majority of languages i know (C++, C#, python, JavaScript) I can manage objects as having 'signals' (notification about something happens/something needed) and 'slots' (method that can be connected to signal and process notification/do some work). In all mentioned languages I can write something like this:
Object1 = new Object1Class();
Object2 = new Object2Class();
Connect( Object1.ItemAdded, Object2.OnItemAdded );
Now if object1
calls/emits ItemAdded
, the OnItemAdded
method of Object2
will be called. Such loose coupling technique is often referred as 'delegates', 'signal-slot' or 'inversion of control'.
Compared to interface pattern, technique mentioned don't need to group signals into some interfaces. Any object's methods can be connected to any delegate as long as signatures match ( C++Qt even extends this by allowing only partial signature match ). So i don't need to write additional interface code for each methods / groups of methods, provide default implementation for interface methods not used etc.
And i can't see anything like this in Java :(. Maybe i'm looking a wrong way?
You should look at Observable and Observer class in java to achieve signal sort of behavior. The main idea is to make the observer do some action when there is a change in the observable object Classes are java.util.Observable which you object which has to send the signal needs to extend.
Interface is java.util.Observer which your observer classes should implement to act on the signal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With