A concise example on applying the Model-View-Controller (MVC) and Strategy pattern on a legacy Windows Forms application. It accepts a simple string which it sorts in different sorting algorithms. The algorithms are dynamically instatiated with the Strategy pattern. Lastly, the UI is updated with adherence to the MVC pattern.
The flow of data on the MVC pattern can be decomposed in several parts:
- Binding of a model on the view.
- Calling a controller method which invokes a change.
- Parsing of the model from the view into a model accepted by the controller method.
- Validating the parsed model (Optional).
- Returning a view with an updated model.
Concept | Implementation |
---|---|
Binding | View Constructor |
Calling | Events |
Parsing | Custom Parsing |
Validating | Custom Validation |
Returning | ViewManager |
The ViewManager is the core of the MVC implementation. It enables the Views to be updated by closing the stale View with an updated View through an updater function.
public static void UpdateView<T, U>(Form currentView, Func<T,U> updater, T model)
{
var updatedView = updater(model);
Update(currentView, updatedView as Form);
}
public static void Update(Form currentView, Form updatedView)
{
currentView.Close();
currentView.Dispose();
var thread = new Thread(() => Application.Run(updatedView));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
Yeet a Pull Request