James Raitsev
James Raitsev

Reputation: 96411

Accessing reference to a Singleton from Interface, can it be done?

Suppose you have a Singleton A whose getInstance() throws some Exceptions.

Further suppose that A is used everywhere throughout the program and while A.getInstance().doSomethingUseful() is fine, a lot of code inherits from Constants interface and i'd like to declare:

A a = A.getInstance() in Constants, allowing everyone tho implements Constants access to a.

As expected, though, Java complains that method throws Exceptions and as such can't be declared in an interface.

Is there a workaround around it?

Upvotes: 0

Views: 89

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272297

I think this is really not a good idea. You're attempting to tie the lifecycle of that object directly into the structure of the classes implementing that interface.

If you have to use a singleton, then better to reference it explicitly via the getInstance() method. It's relatively intuitive. Make your instantiation exceptions runtime if you have to.

Better still is to accept the premise that the singleton pattern is regarded as an anti-pattern and consider alternatives such as injection-of-control.

Upvotes: 3

irreputable
irreputable

Reputation: 45443

Simply convert the checked exception to unchecked

static A getInstanceA2() throws Error
{
    try
    {   return A.getInstance();   }
    catch(Exception e)
    {   throw new Error(e);   }
}

interface Constants
{
    A a = getInstanceA2();
}

If getInstane() fails, interface Constants will be broken, and your app probably will crash.

If there are circular dependencies among A and Contants, A may observe some uninitialized static fields in Constants

Upvotes: 1

Related Questions