Am I overusing the Singleton pattern?

352 views Asked by At

I am suing freely the Singleton pattern and I was wondering; when is enough, enough? These are all of my Singletons for now. I am not using all of them together as some call the others.

Database db = Database.getInstance(this);  // wrapper for the library
Realm realm = Realm.getInstance(this);  // library I use
AppUtils appUtils = AppUtils.getInstance(this); // app specific functions that manipulate database queries to produce targeted values
Utils utils = Utils.getInstance();
Generator gen = Generator.getInstance(this); // necessary for the library

I was thinking of also doing something like

AppFragments fr = AppFragments.getInstance(this, AttributeCommonInEveryActivity>)

or should I interface it and do BlerpActivity extends BlourpActivity

Finally, to clear any bias that might occur affecting your opinion. I know it seems like that I only use one design pattern, but I am not. I work with design and utility in mind ^_^

1

There are 1 answers

1
James Ko On

Yes. Yes you are. But before I even get to that, I don't think you're even using the singleton pattern.

Take a method like Realm.getInstance(this), and let's say this is a FooClass. If Realm were a singleton, only one instance of it would ever exist. If that's true, then why would you have to pass in this? Would the result be different if you passed in a different FooClass?

Now to the actual problem- the troubles of singletons have been covered many times before, so I won't go into that. Instead, I'll show you an alternative: dependency injection.

Here's the singleton (?) version of your Realm class:

class Realm {
    private static final Realm instance = new Realm();

    public static Realm getInstance(FooClass foo) {
        // black magic with foo
        return instance;
    }
}

// usage:
Realm realm = Realm.getInstance(this);

Now, here's the DI version:

class Realm {
    public Realm(FooClass foo) {
        // black magic with foo
    }
}

// usage:
Realm realm = new Realm(this);

You tell me which one looks shorter.