MVP不仅避免了View和Model之前的耦合,更进一步地隆低了Presenter对View的依赖。View实现了接口IView。此处以一个微小的实例展示,废话不多说,直接上代码。
IView:
public interface IDisplayView { void DisplayInfo(IListblogs); event EventHandler Commit; }
Model:此处以BlogRepostory作为Model提供数据
public class BlogsRepostory { public static IListblogs = new List (); public BlogsRepostory() { } }
Presenter:处理用户请求
public class BlogPresenter { public IDisplayView View { get; private set; } public BlogPresenter(IDisplayView view) { this.View = view; this.View.Commit += new EventHandler(Commit); } public void Initalize() { } protected void Commit(object sender,CommitEventArgs e) { BlogsRepostory.blogs.Add(e.blog); this.View.DisplayInfo(BlogsRepostory.blogs); } }
在UI中实现了IView:
public partial class WebForm1 : System.Web.UI.Page, IDisplayView { public event EventHandlerCommit; public BlogPresenter Presenter { get; private set; } public WebForm1() { this.Presenter = new BlogPresenter(this); } protected void Page_Load(object sender, EventArgs e) { } public void DisplayInfo(IList blogs) { if (blogs != null && blogs.Count > 0) { var sb = new StringBuilder(" "); foreach (var blog in blogs) { sb.AppendFormat("
"); this.Lb_Info.Text = sb.ToString(); } } protected void Btn_Commit_Click(object sender, EventArgs e) { if (Commit != null) { Commit(this, new CommitEventArgs(new BlogInfo { Title = TB_Title.Text, Content = TB_Content.Text })); } } }", blog.Title, blog.Content); } sb.Append(" {0} {1}
功能看上去很简单,提交数据然后再显示出来。无非是把最肤浅的东西拿出来说一说,此模式的精妙之处还不甚了解,望各位高人指点一二,不胜感激......