Search code examples
javamiddlewarestub

Java how to register a class instance so that any class can find


Suppose I have a Java class like this:

public class FibSolver{
    int fib(int n){
        //returns n-th term of fibonacci sequence
    }
}

I want to register an instance of this class (called FibService), just like RMI service does when registering .stub files, so that other classes that need this service can call it doing something like this:

FibSolver f = (FibSolver) FindMyService("FibService");
int fib5 = f.fib(5);

But I'm doing this from the beginning and don't want to use RMI.

It is also possible to have multiple different classes working as public services, so I'd rather have something like a .stub file than static instances of each class.

How can I do this registering/retrieving instances of services thing?


Solution

  • How about creating each "service" as a singleton. I would create an interface of IMyService. The interface will have one function getService. Each service will have its C'Tor as private and implement the getService method to provide the single instance of itself.

    Then register all of these services on a global map with its string name. The map could be a global static member which of course can access the static singlton getters of each service.

    Makes sense?