Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good patterns for loose coupling in Java?

Tags:

java

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?

like image 437
grigoryvp Avatar asked Mar 22 '10 14:03

grigoryvp


1 Answers

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

like image 170
Fazal Avatar answered Sep 23 '22 22:09

Fazal