[[https://www.technical-recipes.com/2015/the-model-view-presenter-pattern-in-c-a-minimalist-implementation/#comment-52755|The Model View Presenter pattern in C# – a minimalist implementation]] {{ :lang:csharp:designpattern:mvc:model_view_presenter_pattern_in_c_technical-recipes.com_2020-04-29_10_46_51_pm_.html |Archive du 10/05/2015 le 29/04/2020}} {{ :lang:csharp:designpattern:mvc:modelviewpresenter.zip | Archive projet du 31/01/2019}}
====Les interfaces====
namespace ModelViewPresenter
{
public interface IView
{
string TextValue { get; }
}
}
namespace ModelViewPresenter
{
public interface IModel
{
void Set(string value);
void Reverse(string value);
}
}
====Contrôleur====
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ModelViewPresenter
{
public class Presenter
{
private readonly IView m_View;
private IModel m_Model;
public Presenter(IView view, IModel model)
{
this.m_View = view;
this.m_Model = model;
}
public void ReverseTextValue()
{
string reversed = ReverseString(m_View.TextValue);
m_Model.Reverse(reversed);
}
public void SetTextValue()
{
m_Model.Set(m_View.TextValue);
}
private static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
}
====Modèle et vue====
namespace ModelViewPresenter
{
public partial class Form1 : Form, IView
{
private Presenter presenter = null;
private readonly Model m_Model;
public Form1(Model model)
{
m_Model = model;
InitializeComponent();
presenter = new Presenter(this, m_Model);
SubscribeToModelEvents();
}
public string TextValue
{
get
{
return textBox1.Text;
}
}
private void Set_Click(object sender, EventArgs e)
{
presenter.SetTextValue();
}
private void Reverse_Click(object sender, EventArgs e)
{
presenter.ReverseTextValue();
}
private void SubscribeToModelEvents()
{
m_Model.TextSet += m_Model_TextSet;
}
void m_Model_TextSet(object sender, CustomArgs e)
{
this.textBox1.Text = e.m_after;
this.label1.Text = "Text changed from " + e.m_before + " to " + e.m_after;
}
}
}
namespace ModelViewPresenter
{
public class Model : IModel
{
private string m_textValue;
public event EventHandler TextSet;
public Model()
{
m_textValue = "";
}
public void Set(string value)
{
string before = m_textValue;
m_textValue = value;
RaiseTextSetEvent(before, m_textValue);
}
public void Reverse(string value)
{
string before = m_textValue;
m_textValue = value;
RaiseTextSetEvent(m_textValue, before);
}
public void RaiseTextSetEvent(string before, string after)
{
TextSet(this, new CustomArgs(before, after));
}
}
public class CustomArgs : EventArgs
{
public string m_before { get; set; }
public string m_after { get; set; }
public CustomArgs(string before, string after)
{
m_before = before;
m_after = after;
}
}
}