开发者

ViewModel and Singleton Pattern

开发者 https://www.devze.com 2023-03-09 18:04 出处:网络
I have one ViewModel for enums handling (few entities in Entity Framework). 1) Philosophically, is it a good practice to use a SINGLETON PATTERN for this ViewModel, because it\'s widespread over all

I have one ViewModel for enums handling (few entities in Entity Framework).

1) Philosophically, is it a good practice to use a SINGLETON PATTERN for this ViewModel, because it's widespread over all application and it's used on many places.

2) Isn't it a problem for ViewModel (and associated ObjectContext) to live 开发者_开发百科for very long time?

Thank you!


This should probably be broken up into two separate questions, but I'll take a stab at both:

  1. No. There's no reason a ViewModel should be a Singleton. You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application. Just because an object is widespread and is used frequently doesn't make it a good candidate for a singleton...it just means that it's a good object.

  2. ViewModels should not have a very long lifetime (another reason you don't want a singleton). In MVVM, the lifespan of a given ViewModel would be as long as the user has the window open and finishes their changes.


Having a singleton ViewModel is entirely valid in specific cases. One example I have used multiple times is a SettingsViewModel. Which needs to be accessed globally by multiple systems within the app. My Settings Model on creation loads up settings from a file, the ViewModel allows me to bind to modify those settings. The singleton allows me to globally access those settings where I need instead of passing them around as parameters.

Entirely valid, in this case.


1) don't do it. see MVVM ViewModels Singleton 2) I don't think it's a good idea to have a viewmodel coupled to an object context. It should be just a viewmodel, providing data to a view; but not tightly coupled to any data persistance technology. Instead, inject services that take care of this, so you can mock them.


The objects only live on the stack as long as the garbage collectors deems them to be necessary. Philosophically no it is not a good idea to use Singleton as it breaks encapsulation. See article: Singleton antipattern


As Justin mentioned, it seems unlikely you'll need your ViewModels to follow the Singleton Pattern. However, as you mentioned, View Models are used throughout the system. Consider pulling common functionality into base classes (if you like inheritance) and/or pull reusable components into objects to take advantage of composition.

An easy way to start this is all the lines of Josh Smith's ViewModelBase and a typical ViewModel's usage of INotifyPropertyChanged.

Give that code a look here: http://mvvmfoundation.codeplex.com/

0

精彩评论

暂无评论...
验证码 换一张
取 消