Model View Controller (MVC) Using C #, Delegates and Events in .net

xiaoxiao2021-03-06  52

Introduction

During my third year at the Fontys University in Holland I bumped into a concept called Model-View-Controller. We created a small test project containing the MVC pattern and incorporated different data structures to get experienced with different programming techniques. I embraced the power of patterns and filled my days and nights reading material produced by the Gang of Four. While I was fooling around with .NET during my traineeship at KSE group BV in Holland I decided to experiment with different patterns like MVC, Singleton, Factory etc. This article Explains The MVC Pattern's Basics and Clears The Big Impletion Question Up With A Decent Practical Example Written in My Favorite Programming Language, C #.

Model View Controller

The actual pattern employed in this example, is Model View Controller (MVC). The Windows Forms component will act as the View. There's a book class which represents the Model. The actual Controller logic is not separated from the View / Model because of MY Primary Design Goals. I Will Publish An Extensive MVC-System in The Near Future Which Will Be Reusable for All Kind of .NET Applications.

Delegates

A delegate is a type-safe method reference. With usage of delegates, programs can dynamically call methods at runtime. In contrast to our MVC pattern delegates provide a solid infrastructure to implant the publish-subscribe notification pattern. For those who have experience with Java I'm Referring to the Observer / Observable Registration FunctionAlity Witch The JDK 1.3 Provides for Exploiting The MVC Pattern in The Java Environment.

Events

An event is common in modern programming languages. The basic usage of events is indicating certain user-defined occurrences inside your program. Events are used to notify certain listeners during the program lifetime. A very good example is button clicks or other dynamic actions in your Programs. Events area again powding by the publish / subscriber pattern.the model

While coding this basic example in order to explore MVC pattern I thought of books obviously. Below displayed is a basic book class implementation. This Book class contains a private member called bookPrice. The basic functionality I want to provide for all object who wish to instantiate my book class is an actual book price, in the case that the price changes, my views will update their views in order to display the actual book price. The idea is simple so lets move on ... see the comments in the code.

Using system;

Namespace MVC

{

Public Class Book

{

// Declare a delegate for the bookpricechanged Event

Public Delegate Void BookPriceChangedHandler (ObjectSender,

BookPriceChangeDeventargs E);

// Declare the bookpricechanged Event Using The BookPriceChangeddeLegate

Public Event BookPriceChangedHandlerbookPriceChanged;

// Instance Variable for Book PRICE

Object _bookprice;

// Property for Book PRICE

Public Object BookPrice

{

set

{

// set the installation variable

_bookprice = value;

// the price change so fire the evenet!

OnbookPriceChanged ();

}

}

// Method to Fire Price CANGED Event Delegate with Proper Name

// this is the methodur bSERVERS Should Be IMplenting!

protected void onbookpricechanged ()

{

BookPriceChanged (this, new bookpricechangedendeventArgs);

}

}

}

So what happened here;... We'd structured the basic layout for the book class Notice the declared delegate and event BookPriceChangedHandler and BookPriceChanged The delegate encapsulates the BookPriceChanged method Later we'll see why, but for know its enough to know that the BookPriceChanged method will be implemented in the object that wishes to observe this book class. As you can see, the method gets called with the BookPriceChangedEventArgs. This argument object contains the public properties the book object encapsulates. This is just the standard way for transporting multiple Parameters Towards Methods. Kind of Basic Programming, So this Should Be Self Explanatory. Lets Take a Brief Look At The BookPriceChangeDeventargs Class.Namespace MVC

{

// Specialized Event Class for the BookPriceChanged Event

Public Class BookPriceChangeDeventArgs: Eventargs

{

// Instance Variable to Store the Book PRICE

Private Object _bookprice;

// Constructor That Sets Book Price

Public BookPriceChangeDeventArgs (ObjectbookPrice)

{

_bookprice = bookprice;

}

// Public property for the book price

Public Object BookPrice

{

get

{

Return_bookprice;

}

}

}

}

Maybe you noticed that I used the object (like in Java the "any") instead of string declaration for my price value. The main reason for this is that while creating this model I did not know what kind of GUI representation I wished to use to show my book price value. In case you wish to add more members to the Book class, for instance a name, author, you should extend this EventArgs class. I would consider giving the class a more abstract name like BookChanged.

The view

Now our model is functional so let's move on to the View. Below is a listing of the view object BookView which subscribes to the book model using a delegate. This way the observer gets notified when the price change events is thrown in the model (the observable). You could pass the private book object through reference to multiple views (think of those smart Adobe Photoshop panels, which are views on the underlying model). In this demo I created a simple two-view system making use of a textbox and A Basic Label to Visualize The Book Model.using System;

Using system.drawing;

Using system.collections;

Using system.componentmodel;

Using system.windows.forms;

Namespace MVC

{

Public Class Bookview: System.Windows.Forms.form

{

Private system.componentmodel.Container Components = NULL;

// Declare Our Delagate and Book Object

Private book.bookpricechangedhandler bookdelegate;

PRIVATE BOOK BOOK;

Private system.windows.Forms.Button button1;

Private system.windows.Forms.TextBox textBox1;

Private system.windows.forms.groupbox groupbox1;

Private system.windows.Forms.TextBox textBox2;

Private system.windows.Forms.groupbox GroupBox2;

Private system.windows.Forms.Label label1;

Public bookView ()

{

InitializationComponent ();

// CREATE New Book Instance

Book = New book ();

// Create a new delegate, Instance and Bind IT

// to the observer's bookpricechanged method

BookDelegate = New book.bookpricechangedhandler (this.bookpricechanged);

// add the delegate to the event

Book.bookpricechanged = bookdelegate;

}

Protected Override Void Dispose (Bool Disposing)

{

IF (Disposing)

{

IF (Components! = NULL)

{

Components.dispose ();

}

}

Base.dispose (Disposing);

}

#Region Windows Form Designer generated codeprivate void initializecomponent ()

{

This.button1 = new system.windows.Forms.Button ();

This.TextBox1 = new system.windows.Forms.TextBox ();

THIS.GroupBox1 = new system.windows.Forms.groupbox ();

This.TextBox2 = new system.windows.Forms.TextBox ();

THIS.GroupBox2 = new system.windows.forms.groupbox ();

THIS.LABEL1 = New System.windows.Forms.label ();

THISPBOX1.SUSPENDLAYOUT ();

this.groupbox2.suspendlayout ();

THIS.SUSPENDLAYOUT ();

//

// Button1

//

This.button1.location = new system.drawing.point (120, 16);

This.button1.name = "button1";

this.button1.tabindex = 0;

This.Button1.Text = "Button1";

This.Button1.click = new system.eventhandler (this.button1_click);

//

// textbox1

//

This.TextBox1.Location = new system.drawing.point (8, 16);

THIS.TEXTBOX1.NAME = "TextBox1";

this.TextBox1.tabindex = 1;

THIS.TEXTBOX1.TEXT = "";

//

// Groupbox1

//

This.GroupBox1.controls.addrange (new system.windows.forms.control [] {

THIS.TEXTBOX2});

this.groupbox1.location = new system.drawing.point (8, 104);

this.groupbox1.name = "groupbox1";

this.groupbox1.size = new system.drawing.size (120, 64);

THIS.GroupBox1.tabindex = 2;

THIS.GroupBox1.tabstop = false;

this.groupBox1.text = "View 1";

//

// textbox2

//

This.TextBox2.Location = new system.drawing.point (8, 32);

THIS.TEXTBOX2.NAME = "TextBox2";

THIS.TEXTBOX2.TABINDEX = 0;

THIS.TEXTBOX2.TEXT = "";

//

// GrouPbox2

//

this.groupbox2.controls.addrange (new system.windows.forms.control [] {

THIS.LABEL1});

THIS.GroupBox2.Location = new system.drawing.point (8, 176); this.groupbox2.name = "groupbox2";

this.groupbox2.size = new system.drawing.size (120, 64);

THIS.GroupBox2.tabindex = 3;

THIS.GROUPBOX2.TABSTOP = FALSE;

this.groupbox2.text = "View 2";

//

// label1

//

THIS.Label1.Location = new system.drawing.point (8, 32);

THIS.LABEL1.NAME = "label1";

this.label1.tabindex = 0;

//

// BookView

//

THIS.AUTOSCALEBASESIZE = New System.drawing.size (5, 13);

THIS.CLIENTSIZE = New System.drawing.size (292, 266);

this.controls.addrange (new system.windows.forms.control] {

THIS.GroupBox2,

THIS.GroupBox1,

this.TextBox1,

THIS.BUTTON1});

THIS.NAME = "BOOKVIEW";

THIS.TEXT = "BookView";

This.GroupBox1.ResumeLayout (false);

This.GroupBox2.ResumeLayout (false);

This.ResumeLayout (false);

}

#ndregion

[Stathread]

Static void main ()

{

Application.run (New BookView ());

}

Public Void BookPriceChanged (Object Sender, MVC.BookPriceChangeDeventArgs E)

{

// Update BookPrice Views

Object bookprice;

BookPrice = E.bookprice;

This.TextBox2.text = BOOKPRICE.TOSTRING ();

THIS.Label1.Text = BOOKPRICE.TOSTRING ();

}

Private void Button1_Click (Object Sender, System.Eventargs E)

{

// Change Book PRICE

Book.bookprice = this.TextBox1.text;

}

}

}

As soon you make changes to the book price, the BookPriceChanged will be triggered in the model. Because the view is registered to the OnBookPriceChanged method, the BookPricechanged will be invoked from the model. The View (observer) implements the BookPriceChanged method so the views get updated according to the rules as specified in the view upon the book model. Confused? Then start toying with this code because you now know the basics concerning a simple MVC! The book class code is reusable for whatever functionality you wish to provide to the Outside world from out your model. Have Fun! Conclusion

I'm sure I've explained the MVC mechanism in the .NET world using C # extensively. In my opinion .NET is a fantastic environment for both starting coders and more experienced coders. You'll need some basic knowledge concerning object oriented programming to Make a Jump Start INTO The .NET Framework. I Enjoy Writing this Article and Hope It Was a Useful Addition for Those Who Read It.

转载请注明原文地址:https://www.9cbs.com/read-115715.html

New Post(0)