Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM ViewModels Singleton

Is it a wrong practice to make all viewModels singleton if you don't need multiple instances of each screen?

like image 243
ns12345 Avatar asked Feb 15 '11 16:02

ns12345


3 Answers

Yes because singletons are evil.

You will probably run into issues where the VMs are holding onto state which could be out of sync with your database and lead to excessive memory consumption. It will be much harder to unit test due to the state being persisted.

like image 95
Tom Dudfield Avatar answered Oct 21 '22 21:10

Tom Dudfield


Singletons:

  • make testing harder
  • give you problems later if you do need more than one of them
  • are hard to control where they are created

So only use the singleton pattern if you have a very good reason to do so - "because you can" is not a good reason.

like image 43
Ian Ringrose Avatar answered Oct 21 '22 22:10

Ian Ringrose


Yes.

First, you may very well be putting yourself in a corner for any extensibility, depending on the singleton implementation. Second, the design probably won't be very clean referring to static singletons everywhere. Third, unit testing will either be difficult or it won't replicate actual class usage, or both. Forth, do having singletons solve any design problems for you? If you are simply trying to save on resources then I would just forget it.

like image 22
Jason Jackson Avatar answered Oct 21 '22 23:10

Jason Jackson