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 ^_^
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 saythis
is aFooClass
. IfRealm
were a singleton, only one instance of it would ever exist. If that's true, then why would you have to pass inthis
? Would the result be different if you passed in a differentFooClass
?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:Now, here's the DI version:
You tell me which one looks shorter.