« Return to Thread: Best way to share object instances between modules?

Re: Best way to share object instances between modules?

by tomwheel :: Rate this Message:

Reply to Author | View in Thread

On 5/12/08, Sergio Lopes <knitter.is@...> wrote:
> Lookup is something I have been looking at, but it doesn't look simple
> to add normal objects to the lookup.
> I'm now faced with the doubt of where/when can/must I put my object
> instance in the lookup?

Hi Sergio,

The Lookup may seem tough at first, but it's actually quite simple and
flexible.  Let me give a quick example.  Imagine that you are writing
an application that will calculate someone's income tax.  This should
break down into three modules:

Module 1: API
    - contains com.example.tax.IncomeTaxCalculator interface
    - has no dependency on any other module

Module 2: implementation
    - contains com.example.tax.ConcreteIncomeTaxCalculator class which
implements the com.example.tax.IncomeTaxCalculator interface
    - depends only on the API module
    - has a file
src/META-INF/services/com.example.tax.IncomeTaxCalculator which
contains only a single line the name of the class implementing that
interface (com.example.tax.ConcreteIncomeTaxCalculator in this case)

Module 3: UI
    - has a UI that gets user input, calculates tax and displays the result
    - depends only on the API module
    - Looks up implementation at runtime like this:

     IncomeTaxCalculator calc =
Lookup.getDefault().lookup(IncomeTaxCalculator.class);

Note that you do not ever need to directly instantiate any type of
IncomeTaxCalculator.  No code, aside from that in Module 2, should
even know the name of the IncomeTaxCalculator implementation class --
everything should use the interface.

--
Tom Wheeler
http://www.tomwheeler.com/

 « Return to Thread: Best way to share object instances between modules?