MVVM을 사용하는 이유는 무엇입니까?
좋아, 나는 MVVM 패턴을 조사해 왔고, 이전에 조사해 보았을 때마다 여러 가지 이유로 포기했다.
- 불필요한 여분의 긴 감기 코딩
- 코더에게 명백한 이점이 없음 (사무실에 디자이너가 없습니다. 현재는 곧 다른 코더가 될 나만)
- 좋은 관행에 대한 많은 리소스 / 문서가 아닙니다! (또는 적어도 찾기가 어렵습니다)
- 이것이 유리한 단일 시나리오를 생각할 수 없습니다.
나는 그것을 다시 포기하려고하는데, 누군가가 위의 이유에 대해 대답하는지 물어볼 것이라고 생각했다.
솔직히 단일 / 파트너 코딩에 이것을 사용하는 이점을 볼 수 없습니다. 10 개의 창이있는 복잡한 프로젝트에서도. 나에게 데이터 집합 좋은의 충분한보기에 의해이 질문에 대해 같은 구속력 브렌트 다음과 같은 질문
누군가가 XAML DataBinding과 비교할 때 MVVM 패턴을 사용하면 시간이 절약되는 예를 보여줄 수 있습니까?
내 바인딩의 100 %는 현재 XAML에서 수행됩니다. 따라서 저는 VM의 요점을 제가 작성하고 의존해야하는 추가 코드로 보지 않습니다.
편집 :
오후에 MVVM에 대해 조사한 후 마침내이 답변 에서 진정한 이점을 깨닫게 한 것을 발견했습니다 .
요약
- 모든 패턴의 사용은 상황에 따라 다르며 이점 (있는 경우)은 항상 복잡성 감소에 있습니다.
- MVVM은 GUI 응용 프로그램에서 클래스간에 책임을 분배하는 방법을 안내합니다.
- ViewModel은 모델의 데이터를보기에 맞는 형식으로 투영합니다.
- 사소한 프로젝트의 경우 MVVM이 필요하지 않습니다. 보기 만 사용하면 충분합니다.
- 간단한 프로젝트의 경우 ViewModel / Model 분할이 불필요 할 수 있으며 Model과 View를 사용하는 것만으로도 충분합니다.
- Model 및 ViewModel은 처음부터 존재할 필요가 없으며 필요할 때 도입 할 수 있습니다.
패턴을 사용할 때와 피해야 할 때
충분히 간단한 응용 프로그램의 경우 모든 디자인 패턴이 과도합니다. 눌렀을 때 "Hello world"를 표시하는 단일 버튼을 표시하는 GUI 애플리케이션을 작성한다고 가정합니다. 이 경우 MVC, MVP, MVVM과 같은 디자인 패턴은 모두 많은 복잡성을 추가하지만 가치는 전혀 추가하지 않습니다.
일반적으로 디자인 패턴이 어느 정도 적합하다는 이유로 도입하는 것은 항상 잘못된 결정입니다. 전체 복잡성을 직접 줄이거 나 익숙하지 않은 복잡성을 익숙한 복잡성으로 대체하여 복잡성을 줄이려면 디자인 패턴을 사용해야합니다. 디자인 패턴이이 두 가지 방법 중 하나로 복잡성을 줄일 수 없으면 사용하지 마십시오.
익숙하고 익숙하지 않은 복잡성을 설명하려면 다음 두 가지 문자 시퀀스를 사용하십시오.
- "D. € | Ré % dfà? c"
- "CorrectHorseBatteryStaple"
두 번째 문자 시퀀스는 첫 번째 시퀀스 길이의 두 배이지만 첫 번째 시퀀스보다 읽기 쉽고 쓰기가 빠르며 기억하기 쉽습니다. 모두 더 친숙하기 때문입니다. 코드의 익숙한 패턴도 마찬가지입니다.
이 문제는 독자가 익숙 함을 고려할 때 또 다른 차원을 얻습니다. 일부 독자는 위의 암호보다 "3.14159265358979323846264338327950"을 기억하기가 더 쉽습니다. 일부는 그렇지 않습니다. 따라서 MVVM의 특징을 사용하려면 사용중인 특정 언어 및 프레임 워크에서 가장 일반적인 형식을 반영하는 것을 사용하십시오.
MVVM
즉, 예제를 통해 MVVM의 주제를 살펴 보겠습니다. MVVM은 클래스 당 책임의 수를 작고 잘 정의 된 상태로 유지하면서 적은 수의 클래스를 갖는 것을 목표로 GUI 응용 프로그램의 클래스 간 (또는 레이어 간-나중에 자세히 설명)에 책임을 분배하는 방법을 안내합니다.
'적절한'MVVM은 "어딘가"에서 가져온 데이터를 처리하는 중간 정도의 복잡한 애플리케이션을 가정합니다. 데이터베이스, 파일, 웹 서비스 또는 수많은 다른 소스에서 데이터를 가져올 수 있습니다.
예
이 예에서는 View
및 두 개의 클래스가 Model
있지만 ViewModel
. 은 Model
시작시 읽고 응용 프로그램이 종료 될 때 저장하는 csv 파일을 사용자가 데이터에 적용한 모든 변경 사항과 함께 저장합니다. 는 View
표시로부터 데이터하는 창 클래스입니다 Model
테이블과는 사용자가 데이터를 편집 할 수 있습니다. csv 콘텐츠는 다음과 같습니다.
ID, Name, Price
1, Stick, 5$
2, Big Box, 10$
3, Wheel, 20$
4, Bottle, 3$
새로운 요구 사항 : 유로로 가격 표시
이제 응용 프로그램을 변경하라는 메시지가 표시됩니다. 데이터는 USD로 표시된 가격을 포함하는 "가격"열이 이미있는 2 차원 그리드로 구성됩니다. 미리 정의 된 환율에 따라 USD 가격 외에 유로로 가격을 표시하는 새 열을 추가해야합니다. csv 파일의 형식은 다른 응용 프로그램이 동일한 파일로 작동하고 이러한 다른 응용 프로그램이 우리의 통제를받지 않기 때문에 변경되어서는 안됩니다.
가능한 해결책은 단순히 새 열을 Model
클래스에 추가하는 것 입니다. 이것은 Model
csv에 노출되는 모든 데이터를 저장 하기 때문에 최상의 솔루션이 아닙니다. csv에 새로운 유로 가격 열이 필요하지 않습니다. 따라서의 변경 Model
은 사소한 것이 아니며 Model 클래스가 수행하는 작업, 즉 코드 냄새 를 설명하는 것도 더 어렵습니다 .
에서 변경할 수도 View
있지만 현재 애플리케이션은 데이터 바인딩을 사용하여 Model
클래스에서 제공하는 데이터를 직접 표시합니다 . 우리의 GUI 프레임 워크는 테이블이 데이터를 데이터 소스에 바인딩 할 때 우리가 테이블에 추가로 계산 된 열을 소개하는 것을 허용하지 않기 때문에, 우리는에 큰 변화를 만들 필요가 View
제작,이 작품을 만들기 위해 View
더 많은 복잡한 .
ViewModel 소개
There is no ViewModel
in the application because until now the Model
presents the data in exactly the way the Csv needs it, which is also the way the View
needed it. Having a ViewModel
between would have been added complexity without purpose. But now that the Model
no longer presents the data in the way the View
needs it, we write a ViewModel
. The ViewModel
projects the data of the Model
in such a way that the View
can be simple. Previously the View
class subscribed to the Model
class. Now the new ViewModel
class subscribes to the Model
class, and exposes the Model
's data to the View
- with an extra column displaying the price in Euros. The View
no longer knows the Model
, 지금 만이 알고 ViewModel
, 어느 지점에서 View
같은 외모 Model
전에했던 - 노출 된 데이터가 새로운 읽기에만 열을 포함하는 것을 제외하고.
새로운 요구 사항 : 데이터 형식을 지정하는 다른 방법
다음 고객 요청은 데이터를 테이블의 행으로 표시하지 않고 대신 각 항목 (일명 행)의 정보를 카드 / 상자로 표시하고 화면에 20 개의 상자를 4x5 그리드로 표시하여 20 개를 표시해야한다는 것입니다. 한 번에 상자. 우리는 View
단순한 논리를 유지했기 때문에 단순히 View
고객이 원하는대로하는 새로운 클래스로 완전히 대체합니다 . 물론 이전을 선호하는 다른 고객이 View
있으므로 이제 둘 다 지원해야합니다. 모든 공통 비즈니스 로직이 이미 ViewModel
문제가되지 않는 부분 에 있기 때문입니다. 그래서 우리는 View 클래스의 이름을으로 바꾸고 TableView
새로운CardView
카드 형식으로 데이터를 표시하는 클래스. 우리는 또한 시작 기능에서 한 줄의 코드를 작성해야 할 것입니다.
새로운 요구 사항 : 동적 환율
다음 고객 요청은 사전 정의 된 환율을 사용하는 대신 인터넷에서 환율을 가져 오는 것입니다. 이것이 우리가 "레이어"에 대한 이전 진술을 다시 살펴 보는 지점입니다. 우리는 Model
환율을 제공하기 위해 클래스를 변경하지 않습니다 . 대신 우리는 환율을 제공하는 완전히 독립적 인 추가 클래스를 작성 (또는 찾습니다). 이 새로운 클래스는 모델 계층의 일부가되며 ViewModel
csv-Model 및 exchange-rate-Model의 정보를 통합 한 다음 View
. 이 변경을 위해 이전 Model 클래스와 View 클래스를 건드릴 필요조차 없습니다. 글쎄, 우리는 Model 클래스의 이름을로 바꿔야 CsvModel
하고 우리는 새로운 클래스를라고 부릅니다 ExchangeRateModel
.
우리가 한 대신 우리는 모두에서 기능의 상당한 양을 제거해야하기 때문에 더 높은 것 이제 뷰 모델을 소개하는, 그래서 작업의 양을 지금까지 기다렸다했을 때 우리는 뷰 모델을 도입하지 않았다면 View
과 Model
및 이동 기능을 ViewModel
.
단위 테스트에 대한 후기
MVVM의 주요 목적은 Model과 ViewModel의 코드를 Unit Test에 넣을 수 있다는 것이 아닙니다. MVVM의 주요 목적은 코드가 잘 정의 된 적은 수의 책임을 가진 클래스로 나뉘는 것입니다. 소수의 잘 정의 된 책임을 가진 클래스로 구성된 코드를 갖는 몇 가지 이점 중 하나는 코드를 단위 테스트 아래에 두는 것이 더 쉽다는 것입니다. 훨씬 더 큰 이점은 코드를 이해, 유지 관리 및 수정하기가 더 쉽다는 것입니다.
패턴을 구현하고 모범 사례를 따르는 것은 종종 무의미한 추구처럼 느껴지지만 몇 달 후에 상사가 기능을 추가하거나 조정하도록 요청하면 전환자가됩니다. MVVM (및 일반적인 패턴)을 사용하면 실제로 자신의 코드를 따르고 몇 주 또는 몇 달이 아닌 최악의 경우 몇 시간 또는 며칠 안에 요구 사항을 충족 할 수 있습니다. (이 변경 사항은 새로운 기능을 추가하기 전에 처음에 수행 한 작업을 파악하는 데 몇 주를 소비하는 것보다 코드 몇 줄에 불과할 것입니다.)
후속 조치 : 패턴과 모범 사례는 실제로 초기 개발 속도를 늦추고 관리 및 엔지니어링 모두에게 어려운 판매입니다. 투자 회수 (비즈니스 관점에서 ROI)는 실제로 유지 관리 가능하고 확장 가능하며 확장 가능한 잘 구조화 된 코드에서 비롯됩니다.
예를 들어, MVVM을 올바르게 따르면 데이터 및 비즈니스 로직에 영향을주지 않고 전체 뷰를 교체하는 등 디스플레이 로직을 매우 크게 변경할 수 있습니다.
모델에 데이터 세트를 사용 하는 것에 대한 생각 : (실제로 이것도 마찬가지입니다.) 데이터 세트는 애플리케이션에서 모델 데이터를 이동하는 완벽하게 유효한 방법처럼 보입니다. 문제는 데이터 항목을 식별하는 방법에 있습니다. 데이터가 행과 열에 저장되기 때문에 열 이름 또는 색인으로 조회를 수행하고 특정 행을 필터링해야합니다. 이러한 논리 비트는 애플리케이션에서 논리를 연결하는 데 매직 문자열과 숫자를 사용해야 함을 의미합니다. 유형이 지정된 데이터 세트를 사용하면이 문제의 일부가 완화되지만 완전히 완화되지는 않습니다. 형식화 된 데이터 세트를 사용하면 MVVM에서 벗어나 UI와 데이터 소스 간의 더 긴밀한 결합으로 이동할 수 있습니다.
GUI와 프로그램 로직을 분리하는 데 도움이됩니다. 그것들을 혼합하면 특히 프로젝트가 시간이 지남에 따라 성장할 때 응용 프로그램을 유지하기가 매우 어려울 수 있습니다.
에서 여기 :
개발자로서 왜 Model-View-ViewModel 패턴에 관심을 가져야합니까? 이 패턴은 WPF 및 Silverlight 개발 모두에 많은 이점을 제공합니다. 계속하기 전에 스스로에게 물어보십시오.
- 프로젝트를 디자이너와 공유해야하고 디자인 작업과 개발 작업이 거의 동시에 진행될 수있는 유연성이 필요합니까?
- 솔루션에 대한 철저한 단위 테스트가 필요합니까?
- 조직의 프로젝트 내부와 전체에서 재사용 가능한 구성 요소를 갖는 것이 중요합니까?
- 코드베이스에서 다른 로직을 리팩토링하지 않고도 사용자 인터페이스를 변경할 수있는 유연성을 원하십니까?
If you answered "yes" to any of these questions, these are just a few of the benefits that using the MVVM model can bring for your project.
- It is easier to work with designers (not programmers, just people using Blend)
- Code is testable (unit tests)
- It is much easier to change view without messing with the rest of the code
- While you are developing UI you can mock model and develop your interface without running real service (just using mock data from model). Then you just flip flag and connect to the service.
There are a lot of good things about MVVM, but maybe the most important thing is the ability to test your code (Unit testing the ViewModels).
The lack of connection between the view and viewmodel really helps the loose coupling as well. It becomes really easy to reuse the components you code.
From Josh Smith's article on MVVM:
In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free and fast regression testing, which helps reduce the cost of maintaining an application over time.
For me, this is the most important reason to use MVVM.
Before, I would have controls which mashed the view and viewmodel together. But a view essentially has mouse and keyboard events as input, and drawn pixels as output. How do you unit test something like that? MVVM makes this problem go away as it separates the untestable view from the testable viewmodel, and keeps the view layer as thin as possible.
Read the introduction into MVVM in this article
In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler's Presentation Model, in that both patterns feature an abstraction of a View, which contains a View's state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.
..
Unlike the Presenter in MVP, a ViewModel does not need a reference to a view. The view binds to properties on a ViewModel, which, in turn, exposes data contained in model objects and other state specific to the view. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model is completely oblivious to the fact that the ViewModel and view exist. This is a very loosely coupled design, which pays dividends in many ways, as you will soon see.
Also the article explains why to use these gui patterns:
It is unnecessary and counterproductive to use design patterns in a simple "Hello, World!" program. Any competent developer can understand a few lines of code at a glance. However, as the number of features in a program increases, the number of lines of code and moving parts increase accordingly. Eventually, the complexity of a system, and the recurring problems it contains, encourages developers to organize their code in such a way that it is easier to comprehend, discuss, extend, and troubleshoot. We diminish the cognitive chaos of a complex system by applying well-known names to certain entities in the source code. We determine the name to apply to a piece of code by considering its functional role in the system.
Developers often intentionally structure their code according to a design pattern, as opposed to letting the patterns emerge organically. There is nothing wrong with either approach, but in this article, I examine the benefits of explicitly using MVVM as the architecture of a WPF application. The names of certain classes include well-known terms from the MVVM pattern, such as ending with "ViewModel" if the class is an abstraction of a view. This approach helps avoid the cognitive chaos mentioned earlier. Instead, you can happily exist in a state of controlled chaos, which is the natural state of affairs in most professional software development projects!
I'm still coming to grips with the pattern myself, but I do think it's valuable. The biggest challenge right now is that the approach is still quite new and therefore there is a lot of confusion and certain key components of the pattern are still awkward to implement. I've discovered a few things that have helped me a lot to make cleaner implementations of the pattern:
I make heavy use of the RelayCommand from Josh Smith's MVVM Foundation. This makes the binding from View to ViewModel via Commands much cleaner.
I use AOP to ease the pain of implementing INotifyPropertyChanged. I'm currently using Postsharp, though I believe there are other tools that can do this. If I hadn't discovered this, I probably would've given up by now, as the boilerplate code to implement it manually was really bugging me.
I've had to invert my approach to how the software is implemented. Instead of having a dictator class that tells all of its minions what to do, which in turn use their minions, my software becomes more a matter of loosely coupled services that say:
This is what I know how to do
These are the things I need to have done
When you begin to structure your code in this way and use tools that make it easy to wire up the dependencies (there are a wide range of IoC frameworks to choose from), I've found it eases some of the awkwardness of MVVM, as you can reduce the boilerplate code associated with injecting the Models into the ViewModels and locating various View Services (such as displaying file dialogs) for your ViewModels to consume.
It's a huge investment to learn this different approach and, as with any major shift in implementation, productivity is much lower when you first start using it. However, I'm beginning to see some light at the end of the tunnel and I believe that, once I've mastered the messy details, my applications will be cleaner and much more maintainable.
To address the question about INotifyPropertyChanged via Postsharp, I use an Aspect based on the example here. I've customized it a bit for my use, but that gives you the gist of it. With this, I just tag the class [NotifyPropertyChanged] and all of the public properties will have the pattern implemented in their setters (even if they are auto-property setters). It feels much cleaner to me, as I no longer have to worry about whether I want to take the time to make the class implement INotifyPropertyChanged. I can just add the attribute and be done with it.
I agree that using MVVM put more weight on our shoulders by writing ore code, but look at the bright side where everything is isolated then if you are a designer so you can design your program and other can code it for you and other does the Database layer for you,look how maintainable enviroment you will be in especially in large enterprise applications if you would not use MVVM ,then the maintainance is almost killing.... I myself used it when developing ERP solution now the maintainance is pretty straight forward because of that isolation level
You'll be happy in the long run if you use a pattern like MVVM for all the reasons the others have posted. Remember, you don't need to follow the pattern requirements word-for-word, just make sure you have good separation between your window (View) and your logic (code-behind).
Benefits of MVVM
- Reduced complexity.
- Isolation of Designing and Development.
- Dependency injection.
- Major advantage is when you have a Well MVVM structured Windows Phone application and want to develop same for Windows Metro Desktop, Only thing u want to concentarte on design as the same view model can be used as it is.
Hope it helps.
MVVM is really excessive code.
So what benefits does the MVVM provide?
It's just Seperation of concerns not more. You could also write the ViewModel logic into the Controller. The ViewModel is just repsonsible for doing a conversion (for example and object into a string). By using MVVM you use more object-oriented programming style. By writing the conversion logic into the Controller you use more functional programming style.
So it comes down to having more code with better readability or less code with big Controller files. In conclusion you cannot say you have to use MVVM, because it is better then MVC or so, it is just a personal preference.
Just to be clear why I mention a Controller: MVVM also has Controller-code somewhere. I have no idea why there's a wide consensus to leave the C.
참고URL : https://stackoverflow.com/questions/2653096/why-use-mvvm
'Development Tip' 카테고리의 다른 글
Rails has_many : Join Model의 추가 속성으로 찾기 (0) | 2020.10.31 |
---|---|
참조 된 모든 어셈블리를 앱 도메인에 강제로로드하는 방법이 있습니까? (0) | 2020.10.31 |
"로그 앤 스로우"가 안티 패턴으로 간주되는 이유는 무엇입니까? (0) | 2020.10.31 |
단일 Scrapy 프로젝트에서 서로 다른 스파이더에 대해 서로 다른 파이프 라인을 사용하려면 어떻게해야합니까? (0) | 2020.10.31 |
Express를 사용하여 NodeJS에서 AJAX 요청 감지 (0) | 2020.10.31 |