Using MVP Architecture Pattern

Saying that MVP is a kind of design pattern is incorrect. Actually it is an architecture pattern. MVP, as well as joint, as User Interface (UI) business logic that divides each other. (Separation of Concerns.) In a button click event the host within a procedure to identify and UI to do this is often not correct. The UI can change continuously. Or you want to implement your web or windows application to a mobile.

It is difficult to do that as soon as possible. And ususally it is not very successfull. But by using the Separation of Concerns approach it is possible. Model View Presenter (MVP) is based on this philosophy. What is Model View Presenter?

What is Model View Presenter?

  • M (Model) :  Business logic and data handling processes are executed. It responds in accordance with orders sent by the P (Presenter). After the process of data handling, M sends data to the Presenter or other models.

  • V (View) : Concerned with the presentation of the data to be shown to the end user. V, this information P (Presenter) or is M to, the demands of the end user at the same time transmits P.

  • P (Presenter) The main part of the system which control requests from other elements of the system (M, V) receive appropriate information,Presenter enables users to send requests.The main objective is to separate business logic from UI.

The main objective is to separate the business logic from the UI. Let's see this with a diagram.

ModelViewPresenter_1.png

The difference from a MVC (Model-View-Controller) structure is that MVP is a page control. What does this mean? The presenter controls the page or form when the web page is loaded. By Presenter is activating in the Presenter's constructor. Because the IView interface in the View (UI) has been implemented at the page. The Page or a form is derived from this interface. The Presenter has an IView property in the Constructor. Because of this, an object from Presenter is created in the UI side and if the View class is connected to this interface, the control switches to the Presenter page.

Code

Let's talk about code.

 public class DomainView: IDomainView{
    private IDomainPresenter domainPresenter;    public DomainView()
    {
        this.domainPresenter = new ConcreteDomainPresenter(this);
    }
}

ViewImplementation in application is provided in the example above. The Presenter constructor is called by implementing IDomainView which helps the Presenter to get control of the form.

Model

Model is a domain area that can be the same as a database table model. Also include CRUD events. The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.

Code

 public class Product
    {
        public string Name { getset; }
        public string Model { getset; }
        public string Type { getset; }
        public double StokPrice { getset; }
        public DateTime StokAddedDate { getset; }

        public void Save()
        {
            dbase client = new Sql();
              ListDictionary ld = new ListDictionary();
              ld.Add("@name", Name);
              ld.Add("@model", Model);
              ld.Add("@type", Type);
              ld.Add("@stokPrice", StokPrice);
              ld.Add("@stokAddedDate", StokAddedDate);
              client.UpdateSql(WebConfigurationManager.AppSettings["myKey"].ToString(), "[proc_AddProduct]", ld);
        }

    }


Presenter

The Presenter must notify the Model but the model doesn't have any knowledge of the Presenter. The Presenter is the envoy to provide communication between the Model and View. Also the Presenter has a role to play in the CRUD event. The Presenter passes into View elements (properties, Events etc.) by using a constructor which has an interface is called  IProductEditorView. All of the communications has been transmitted over IProductEditorView. The View class implements from IProductEditorView. The Presenter calls View by IProductEditorView.

Code

public interface IProductEditorView
    {
string ProductName { get; }
        string ProductModel { get; }
        string Type { get; }
        double StokPrice { get; }
        DateTime StokAddedDate { get; }
        event EventHandler<EventArgs> Save;
 }

The above interface calls from the Presenter Constructor.

Code

public class ProductEditorPresenter
    {
        private IProductEditorView mView;
        public ProductEditorPresenter(IProductEditorView view)
        {
            this.mView = view;
            this.Initialize();
        }
        private void Initialize()
        {
            this.mView.Save += new EventHandler<EventArgs>(mView_Save);
        }
        private void mView_Save(object sender, EventArgs e)
        {
            try
            {
                Product product = new Product();
                product.Name = mView.ProductName;
                product.Model = mView.ProductModel;
                product.Type = mView.Type;
                product.StokPrice = mView.StokPrice;
                product.StokAddedDate = mView.StokAddedDate;
                product.Save();

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw;
            }
        }
    }

View

ModelViewPresenter_2.png

The view is a passive interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data. The View doesn't have any knowledge of the Model. The View has a relation with the Presenter using IproductEditorView. The Presenter Class instance is initialized in the View's OnInit event. Communication between the Presenter and the View starts at this point. Look at the following code. The View implements  IproductEditorView.

Code

 public partial class _Default : System.Web.UI.PageIProductEditorView
    {
        private ProductEditorPresenter mPresenter;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.mPresenter = new ProductEditorPresenter(this);
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SaveProcess(object sender, EventArgs e)
        {
            if (this.Save != null)
                this.Save(thisEventArgs.Empty);
        }

        #region IProductEditorView Members

        public string ProductModel
        {
            get { return txtProductModel.Text; }
        }

        public string ProductName
        {
            get { return txtProductName.Text; }
        }

        public DateTime StokAddedDate
        {
            get { return DateTime.Parse(txtDate.Text); }
        }
 
        public double StokPrice
        {
            get { return Convert.ToDouble(txtStokPrice.Text); }
        }
 
        public string Type
        {
            get { return txtProductType.Text; }
        }

        public event EventHandler<EventArgs> Save;

        #endregion
    }
}

Two primary variations

Passive View: The View is as dumb as possible and contains nearly no logic. The Presenter is a middle-man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In the Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.

  • Pro: maximum testability surface; clean separation of the View and Model

  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

  • Pro: by leveraging databinding the amount of code is reduced.

  • Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model. (Stackoverflow-Glenn Block)

Differences between MVC and MVP

MVP

  • An advanced form of MVC.

  • View handles the user gestures and calls the presenter as appropriate

  • The View is completely passive, all interactions with the model must pass through the presenter.

  • Highly supportive of unit testing.

MVC

  • One of the old patterns used to achieve separation of concerns.

  • Controller handles the user gestures and commands model.

  • View has some intelligence. It can query the model directly.

  • Limited support to unit testing.

References

http://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference

http://www.codeproject.com/Articles/288928/Differences-between-MVC-and-MVP-for-Beginners

http://www.codeproject.com/Articles/42967/Model-View-Presenter-via-NET


Similar Articles