<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Grapii &#187; Design Patterns</title>
	<atom:link href="http://www.grapii.com/tag/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.grapii.com</link>
	<description>Personal Site of Raj Patel</description>
	<lastBuildDate>Mon, 06 Sep 2010 13:45:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Model-View-Controller Design Pattern Part 2</title>
		<link>http://www.grapii.com/2009/12/model-view-controller-design-pattern-part-2/</link>
		<comments>http://www.grapii.com/2009/12/model-view-controller-design-pattern-part-2/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 00:44:00 +0000</pubDate>
		<dc:creator>grapii</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.grapii.com/2009/12/model-view-controller-design-pattern-part-2/</guid>
		<description><![CDATA[In Part 1 of the series I explained the concept of the Model-View-Controller (MVC) pattern.&#160; This final part shows you how to create an ASP.NET MVC application in Visual Studio. 
 
In this walkthrough, you will create and run the sample MVC application. Then you will customize the application by adding a controller and a [...]]]></description>
			<content:encoded><![CDATA[<p>In Part 1 of the series I explained the concept of the <a href="http://www.grapii.com/2009/11/model-view-controller-design-pattern-part-1/">Model-View-Controller</a> (MVC) pattern.&#160; This final part shows you how to create an ASP.NET MVC application in Visual Studio. </p>
<p> <span id="more-644"></span>
<p>In this walkthrough, you will create and run the sample MVC application. Then you will customize the application by adding a controller and a view.</p>
<h2>Prerequisites</h2>
<p>In order to complete this walkthrough, you will need: </p>
<ul>
<li>Microsoft Visual Studio 2008 Service Pack 1. </li>
<li>ASP.NET MVC 1.0. </li>
</ul>
<p>You can download and install the ASP.NET MVC framework in the following ways: </p>
<ul>
<li>Install the framework using the Microsoft Web Platform Installer. You can download the installer from the <a href="http://go.microsoft.com/fwlink/?LinkID=148931&amp;clcid=0x409">installation page</a> on the Microsoft Web gallery site. </li>
<li>Download the framework from the <a href="http://go.microsoft.com/fwlink/?LinkId=144444">ASP.NET MVC 1.0</a> page on the Microsoft Download Center. </li>
</ul>
<h2>Creating a New MVC Project</h2>
<ol>
<li>On the <strong>File</strong> menu, click <strong>New Project</strong>.       <br />The New Project dialog box is displayed.       <br /><a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc001.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc001" alt="mvc001" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc001-thumb.png" width="400" height="323" /></a> </li>
<li>In the upper-right corner, make sure that <strong>.NET Framework 3.5</strong> is selected. </li>
<li>Under <strong>Project types</strong>, expand <strong>Visual Basic</strong> and then click <strong>Web</strong>. </li>
<li>Under <strong>Visual Studio installed templates</strong>, select <strong>ASP.NET MVC Web Application</strong>. </li>
<li>In the <strong>Name</strong> box, enter <strong>MvcBasicWalkthrough</strong>. </li>
<li>In the <strong>Location</strong> box, enter a name for the project folder. </li>
<li>If you want the name of the solution to differ from the project name, enter a name in the <strong>Solution Name</strong> box. </li>
<li>Select <strong>Create directory for solution</strong>. </li>
<li>Click <strong>OK</strong>.       <br />The Create Unit Test Project dialog box is displayed.       <br /><a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc002.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc002" alt="mvc002" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc002-thumb.png" width="400" height="260" /></a> </li>
<li>Select <strong>No, do not create a unit test project.</strong> </li>
<li>Click <strong>OK</strong>.       <br />The new MVC application project and a test project are generated. </li>
</ol>
<h2>Examining the MVC Project</h2>
<p>The following illustration shows the folder structure of a newly created MVC solution.&#160; <br /><a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc0031.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc003" alt="mvc003" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc003-thumb1.png" width="300" height="341" /></a> </p>
<p>The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:</p>
<ul>
<li>
<p>Content, which is for content support files. This folder contains the cascading style sheet (.css file) for the application.</p>
</li>
<li>
<p>Controllers, which is for controller files. This folder contains the application&#8217;s sample controllers, which are named <tt>AccountController</tt> and <tt>HomeController</tt>. The <tt>AccountController</tt> class contains login logic for the application. The <tt>HomeController</tt> class contains logic that is called by default when the application starts.</p>
</li>
<li>
<p>Models, which is for data-model files such as LINQ-to-SQL .dbml files or data-entity files.</p>
</li>
<li>
<p>Scripts, which is for script files, such as those that support ASP.NET AJAX and jQuery.</p>
</li>
<li>
<p>Views, which is for view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an About page view. The Shared folder contains the master-page view for the application.</p>
</li>
</ul>
<p>The newly generated MVC project is a complete application that you can compile and run without change. The following illustration shows what the application looks like when it runs in a browser.<a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc004.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc004" alt="mvc004" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc004-thumb.png" width="400" height="220" /></a>The unit-test project is also ready to compile and run. For this walkthrough, you will add a controller with an action method and a view.</p>
<h2>Adding a Controller</h2>
<p><a></a></p>
<p>You will now add a controller that contains logic for downloading city maps from the Microsoft Virtual Earth Web service.</p>
<ol>
<li>In <strong>Solution Explorer</strong>, right-click the <strong>Controllers</strong> folder, click <strong>Add</strong>, and then click <strong>Controller</strong>.       <br />The Add Controller dialog box is displayed.<a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc005.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc005" alt="mvc005" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc005-thumb.png" width="400" height="168" /></a> </li>
<li>In the <strong>Name</strong> box, type <strong>MapsController</strong>.       <br />The ASP.NET MVC framework requires controller names to end with &quot;Controller&quot;, such as <tt>HomeController</tt>, <tt>GameController</tt>, or <tt>MapsController</tt>. </li>
<li>Clear the <strong>Add action methods for Create, Update, and Details scenarios</strong> check box. </li>
<li>Click <strong>Add</strong>.       <br />Visual Studio adds the <tt>MapsController</tt> class to the project and opens it in the editor. </li>
</ol>
<h2>Adding Code to the Action Method</h2>
<p>You will now add code to the <tt>MapsController</tt> class for the <tt>ViewMaps</tt> action method in order to render the <tt>Maps</tt> view.</p>
<ol>
<li>Open the <tt>MapsController</tt> class and replace the <tt>ViewMaps</tt> action-method stub with the following code in order to render the <tt>Maps</tt> view.
<pre>Function ViewMaps() As ActionResult
    Return View()
End Function</pre>
</li>
<li>Save and close the file. </li>
</ol>
<h2>Adding a View</h2>
<p><a></a></p>
<p>Next, you will add a <tt>Maps</tt> view. To keep the views organized, you will first add a Maps folder under the Views folder.</p>
<ol>
<li>Open the <tt>MapsController</tt> class, right-click inside the <tt>ViewMaps</tt> action method, and then click <strong>Add View</strong>.
<p>The Add View dialog box is displayed.</p>
<p><a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc006.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc006" alt="mvc006" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc006-thumb.png" width="400" height="410" /></a> </li>
<li>In the <strong>View name</strong> box, enter <strong>ViewMaps.aspx</strong>. </li>
<li>Clear the <strong>Create a partial view (.ascx)</strong> check box and the <strong>Create a strongly-typed view</strong> check box. </li>
<li>Select the <strong>Select master page</strong> check box and set the master page to <strong>~/Views/Shared/Site.Master</strong>. </li>
<li>Set <strong>ContentPlaceHolder ID</strong> to &quot;MainContent&quot;. </li>
<li>Click <strong>Add</strong>.
<p>The new view is added to the project in the Maps folder </li>
</ol>
<h2>Adding Content to the View</h2>
<p>Next, you will add content to the new view.</p>
<ol>
<li>Open ViewMaps.aspx and add the following content inside the <strong>Content</strong> element:
<pre>&lt;h2&gt;My City Maps&lt;/h2&gt;
Select map:
&lt;select onclick=&quot;GetMap(value);&quot;&gt;
    &lt;option value=&quot;Seattle&quot;&gt;Seattle, WA&lt;/option&gt;
    &lt;option value=&quot;LasVegas&quot;&gt;Las Vegas, NV&lt;/option&gt;
    &lt;option value=&quot;SaltLake&quot;&gt;Salt Lake City, UT&lt;/option&gt;
    &lt;option value=&quot;Dallas&quot;&gt;Dallas, TX&lt;/option&gt;
    &lt;option value=&quot;Chicago&quot;&gt;Chicago, IL&lt;/option&gt;
    &lt;option value=&quot;NewYork&quot;&gt;New York, NY&lt;/option&gt;
    &lt;option value=&quot;Rio&quot;&gt;Rio de Janeiro, Brazil&lt;/option&gt;
    &lt;option value=&quot;Paris&quot;&gt;Paris, France&lt;/option&gt;
    &lt;option value=&quot;Naples&quot;&gt;Naples, Italy&lt;/option&gt;
    &lt;option value=&quot;Keta&quot;&gt;Keta, Ghana&lt;/option&gt;
    &lt;option value=&quot;Beijing&quot;&gt;Beijing, China&lt;/option&gt;
    &lt;option value=&quot;Sydney&quot;&gt;Sydney, Australia&lt;/option&gt;
&lt;/select&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div id='earthMap' style=&quot;position:relative; width:400px; height:400px;&quot;&gt;
&lt;/div&gt;
&lt;script charset=&quot;UTF-8&quot; type=&quot;text/javascript&quot;
    src=&quot;http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&amp;mkt=en-us&quot;&gt;
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    var map = null;
    var mapID = '';

    function GetMap(mapID)
    {
        switch (mapID)
        {
            case 'Seattle':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(47.6, -122.33), 10 ,'i', true);
                break;
            case 'LasVegas':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(36.17, -115.14), 10 ,'i' ,true);
                break;
            case 'SaltLake':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(40.75, -111.89), 10 ,'i' ,true);
                break;
            case 'Dallas':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(32.78, -96.8), 10 ,'i' ,true);
                break;
            case 'Chicago':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(41.88, -87.62), 10 ,'i' ,true);
                break;
            case 'NewYork':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(40.7, -74), 10 ,'i' ,true);
                break;
            case 'Rio':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(-22.91, -43.18), 10 ,'i' ,true);
                break;
            case 'Paris':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(48.87, 2.33), 10 ,'i' ,true);
                break;
            case 'Naples':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(40.83, 14.25), 10 ,'i' ,true);
                break;
            case 'Keta':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(5.92, 0.983), 10 ,'i' ,true);
                break;
            case 'Beijing':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(39.91, 116.39), 10 ,'i' ,true);
                break;
            case 'Sydney':
                map = new VEMap('earthMap');
                map.LoadMap(new VELatLong(-33.86, 151.21), 10 ,'i' ,true);
         }
    }
&lt;/script&gt;</pre>
<p>This markup defines a drop-down list for selecting a map and the JavaScript logic for retrieving the selected map from the Microsoft Virtual Earth Web service. </li>
<li>Save and close the file. </li>
</ol>
<h2>Adding a Tab to the Master-Page Menu</h2>
<p>You will now add an item to the master-page menu that calls the <tt>ViewMaps</tt> action method.</p>
<ol>
<li>In the Shared folder, open the Site.master file and locate the unordered list (ul element) in the div element whose ID is &quot;menucontainer&quot;. </li>
<li>Add the following code to the list between the <strong>Index</strong> and <strong>About Us</strong> tabs:
<pre>&lt;li&gt;&lt;%= Html.ActionLink(&quot;My City Maps&quot;, &quot;ViewMaps&quot;, &quot;Maps&quot;)%&gt;&lt;/li&gt;</pre>
<p>The <tt>ActionLink</tt> method is a helper method that links to an action method. It takes the following parameters: the text for the link, the name of the action method, and the name of the controller. </li>
<li>Save and close the file. </li>
</ol>
<h2>Testing the MVC Application</h2>
<p>You can now test the application.</p>
<ol>
<li>In <strong>Solution Explorer</strong>, select the walkthrough project and press CTRL+F5 to run the application.
<p>The Index.aspx page is displayed, which includes the tabs that are defined in the master page. </li>
<li>Click the <strong>My City Maps</strong> tab.
<p>The My City Maps page is displayed. Select any map to see it displayed.</p>
<p><a href="http://www.grapii.com/wp-content/uploads/2010/01/mvc007.png" rel="lightbox[644]"><img style="display: block; float: none; margin-left: auto; margin-right: auto" title="mvc007" alt="mvc007" src="http://www.grapii.com/wp-content/uploads/2010/01/mvc007-thumb.png" width="400" height="378" /></a> </li>
</ol>
<h2>Next Steps</h2>
<p>This walkthrough gives you a first look at creating an MVC application and working with unit tests in ASP.NET MVC. From here, you might want to learn more about the ASP.NET MVC framework. The following list suggests topics for additional learning.</p>
<ul>
<li>
<p>For more information about MVC controllers<br />
      <br />&#160;&#160; see <a href="http://msdn.microsoft.com/en-us/library/dd410269.aspx">Controllers and Action Methods in MVC Applications</a>.</p>
</li>
<li>
<p>For more information about MVC views<br />
      <br />&#160;&#160; see <a href="http://msdn.microsoft.com/en-us/library/dd410123.aspx">Views and UI Rendering in MVC Applications</a>.</p>
</li>
<li>
<p>For more information about MVC models<br />
      <br />&#160;&#160; see <a href="http://msdn.microsoft.com/en-us/library/dd410405.aspx">Models and Model Binders in MVC Applications</a>.</p>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.grapii.com/2009/12/model-view-controller-design-pattern-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Model-View-Controller Design Pattern Part 1</title>
		<link>http://www.grapii.com/2009/11/model-view-controller-design-pattern-part-1/</link>
		<comments>http://www.grapii.com/2009/11/model-view-controller-design-pattern-part-1/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 01:09:00 +0000</pubDate>
		<dc:creator>grapii</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.grapii.com/2009/11/model-view-controller-design-pattern-part-1/</guid>
		<description><![CDATA[Part one of a two-part post describing the Model-View-Controller design pattern in context of web applications.

Context
The purpose of many computer systems is to retrieve data from a data store and display it for the user. After the user changes the data, the system stores the updates in the data store. Because the key flow of [...]]]></description>
			<content:encoded><![CDATA[<p>Part one of a two-part post describing the Model-View-Controller design pattern in context of web applications.</p>
<p><span id="more-596"></span></p>
<h2>Context</h2>
<p>The purpose of many computer systems is to retrieve data from a data store and display it for the user. After the user changes the data, the system stores the updates in the data store. Because the key flow of information is between the data store and the user interface, you might be inclined to tie these two pieces together to reduce the amount of coding and to improve application performance. However, this seemingly natural approach has some significant problems. One problem is that the user interface tends to change much more frequently than the data storage system. Another problem with coupling the data and user interface pieces is that business applications tend to incorporate business logic that goes far beyond data transmission.</p>
<h2>Problem</h2>
<p>How do you modularize the user interface functionality of a Web application so that you can easily modify the individual parts?</p>
<h2>Forces</h2>
<p>The following forces act on a system within this context and must be reconciled as you consider a solution to the problem:</p>
<ul>
<li>User interface logic tends to change more frequently than business logic, especially in Web-based applications. For example, new user interface pages may be added, or existing page layouts may be shuffled around. After all, one of the advantages of a Web-based thin-client application is the fact that you can change the user interface at any time without having to redistribute the application. If presentation code and business logic are combined in a single object, you have to modify an object containing business logic every time you change the user interface. This is likely to introduce errors and require the retesting of all business logic after every minimal user interface change.</li>
<li>In some cases, the application displays the same data in different ways. For example, when an analyst prefers a spreadsheet view of data whereas management prefers a pie chart of the same data. In some rich-client user interfaces, multiple views of the same data are shown at the same time. If the user changes data in one view, the system must update all other views of the data automatically.</li>
<li>Designing visually appealing and efficient HTML pages generally requires a different skill set than does developing complex business logic. Rarely does a person have both skill sets. Therefore, it is desirable to separate the development effort of these two parts.</li>
<li>User interface activity generally consists of two parts: presentation and update. The presentation part retrieves data from a data source and formats the data for display. When the user performs an action based on the data, the update part passes control back to the business logic to update the data.</li>
<li>In Web applications, a single page request combines the processing of the action associated with the link that the user selected with the rendering of the target page. In many cases, the target page may not be directly related to the action. For example, imagine a simple Web application that shows a list of items. The user returns to the main list page after either adding an item to the list or deleting an item from the list. Therefore, the application must render the same page (the list) after executing two quite different commands (adding or deleting)-all within the same HTTP request.</li>
<li>User interface code tends to be more device-dependent than business logic. If you want to migrate the application from a browser-based application to support personal digital assistants (PDAs) or Web-enabled cell phones, you must replace much of the user interface code, whereas the business logic may be unaffected. A clean separation of these two parts accelerates the migration and minimizes the risk of introducing errors into the business logic.</li>
</ul>
<h2>Solution</h2>
<p>The <em>Model-View-Controller (MVC)</em> pattern separates the modelling of the domain, the presentation, and the actions based on user input into three separate classes [Burbeck92]:</p>
<ul>
<li><strong>Model</strong>. The model manages the behaviour and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).</li>
<li><strong>View</strong>. The view manages the display of information.</li>
<li><strong>Controller</strong>. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.</li>
</ul>
<p>Figure 1 depicts the structural relationship between the three objects.</p>
<p align="center"><a href="http://www.grapii.com/wp-content/uploads/2009/11/mvc001.gif" rel="lightbox[596]"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Figure 1" src="http://www.grapii.com/wp-content/uploads/2009/11/mvc001-thumb.gif" border="0" alt="Figure 1" width="300" height="200" /></a> <em>Figure 1: MVC class structure</em></p>
<p>It is important to note that both the view and the controller depend on the model. However, the model depends on neither the view nor the controller. This is one the key benefits of the separation. This separation allows the model to be built and tested independent of the visual presentation. The separation between view and controller is secondary in many rich-client applications, and, in fact, many user interface frameworks implement the roles as one object. In Web applications, on the other hand, the separation between view (the browser) and controller (the server-side components handling the HTTP request) is very well defined.</p>
<p><em>Model-View-Controller </em>is a fundamental design pattern for the separation of user interface logic from business logic. Unfortunately, the popularity of the pattern has resulted in a number of faulty descriptions. In particular, the term &#8220;controller&#8221; has been used to mean different things in different contexts. Fortunately, the advent of Web applications has helped resolve some of the ambiguity because the separation between the view and the controller is so apparent.</p>
<h2>Variations</h2>
<p>In <em>Application Programming in Smalltalk-80: How to use Model-View-Controller (MVC)</em> [Burbeck92], Steve Burbeck describes two variations of <em>MVC</em>: a passive model and an active model.</p>
<p>The passive model is employed when one controller manipulates the model exclusively. The controller modifies the model and then informs the view that the model has changed and should be refreshed (see Figure 2). The model in this scenario is completely independent of the view and the controller, which means that there is no means for the model to report changes in its state. The HTTP protocol is an example of this. There is no simple way in the browser to get asynchronous updates from the server. The browser displays the view and responds to user input, but it does not detect changes in the data on the server. Only when the user explicitly requests a refresh is the server interrogated for changes.</p>
<p align="center"><a href="http://www.grapii.com/wp-content/uploads/2009/11/mvc002.gif" rel="lightbox[596]"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Figure 2" src="http://www.grapii.com/wp-content/uploads/2009/11/mvc002-thumb.gif" border="0" alt="Figure 2" width="300" height="320" /></a> <em>Figure 2: Behaviour of the passive model</em></p>
<p>The active model is used when the model changes state without the controller&#8217;s involvement. This can happen when other sources are changing the data and the changes must be reflected in the views. Consider a stock-ticker display. You receive stock data from an external source and want to update the views (for example, a ticker band and an alert window) when the stock data changes. Because only the model detects changes to its internal state when they occur, the model must notify the views to refresh the display.</p>
<p>However, one of the motivations of using the <em>MVC</em> pattern is to make the model independent from of the views. If the model had to notify the views of changes, you would reintroduce the dependency you were looking to avoid. Fortunately, the <em>Observer</em> pattern [Gamma95] provides a mechanism to alert other objects of state changes without introducing dependencies on them. The individual views implement the <em>Observer </em>interface and register with the model. The model tracks the list of all observers that subscribe to changes. When a model changes, the model iterates through all registered observers and notifies them of the change. This approach is often called &#8220;publish-subscribe.&#8221; The model never requires specific information about any views. In fact, in scenarios where the controller needs to be informed of model changes (for example, to enable or disable menu options), all the controller has to do is implement the <em>Observer </em>interface and subscribe to the model changes. In situations where there are many views, it makes sense to define multiple subjects, each of which describes a specific type of model change. Each view can then subscribe only to types of changes that are relevant to the view.</p>
<p>Figure 3 shows the structure of the active MVC using <em>Observer</em> and how the observer isolates the model from referencing views directly.</p>
<p><a href="http://www.grapii.com/wp-content/uploads/2009/11/mvc003.gif" rel="lightbox[596]"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Figure 3" src="http://www.grapii.com/wp-content/uploads/2009/11/mvc003-thumb.gif" border="0" alt="Figure 3" width="300" height="180" /></a> <em>Figure 3: Using Observer to decouple the model from the view in the active model</em></p>
<p>Figure 4 illustrates how the <em>Observer</em> notifies the views when the model changes. Unfortunately, there is no good way to demonstrate the separation of model and view in a Unified Modelling Language (UML) sequence diagram, because the diagram represents instances of objects rather than classes and interfaces.</p>
<p align="center"><a href="http://www.grapii.com/wp-content/uploads/2009/11/mvc004.gif" rel="lightbox[596]"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Figure 4" src="http://www.grapii.com/wp-content/uploads/2009/11/mvc004-thumb.gif" border="0" alt="Figure 4" width="300" height="361" /></a> <em>Figure 4: Behaviour of the active model</em></p>
<h2>Resulting Context</h2>
<p>Architecting the presentation layer around the <em>MVC</em> pattern results in the following benefits and liabilities:</p>
<h3>Benefits</h3>
<ul>
<li><strong>Supports multiple views</strong>. Because the view is separated from the model and there is no direct dependency from the model to the view, the user interface can display multiple views of the same data at the same time. For example, multiple pages in a Web application may use the same model objects. Another example is a Web application that allows the user to change the appearance of the pages. These pages display the same data from the shared model, but show it in a different way. <strong></strong></li>
<li><strong>Accommodates change</strong>. User interface requirements tend to change more rapidly than business rules. Users may prefer different colours, fonts, screen layouts, and levels of support for new devices such as cell phones or PDAs. Because the model does not depend on the views, adding new types of views to the system generally does not affect the model. As a result, the scope of change is confined to the view.</li>
</ul>
<h3>Liabilities</h3>
<ul>
<li><strong>Complexity</strong>. The <em>MVC</em> pattern introduces new levels of indirection and therefore increases the complexity of the solution slightly. It also increases the event-driven nature of the user-interface code, which can become more difficult to debug.</li>
<li><strong>Cost of frequent updates</strong><em>.</em> Decoupling the model from the view does not mean that developers of the model can ignore the nature of the views. For example, if the model undergoes frequent changes, it could flood the views with update requests. Some views, such as graphical displays, may take some time to render. As a result, the view may fall behind update requests. Therefore, it is important to keep the view in mind when coding the model. For example, the model could batch multiple updates into a single notification to the view.</li>
</ul>
<h2>Example</h2>
<p><a href="http://www.grapii.com/2009/12/model-view-controller-design-pattern-part-2/">Part two</a> of this post will describe implementing the <em>MVC</em> model in ASP.NET.</p>
<p class="note"><strong>Acknowledgements:</strong><br />
<em>Model-View-Controller</em> began as a framework developed by Trygve Reenskaug for the Smalltalk platform in the late 1970s [Fowler03]. The version you have just read references the following works:<br />
[<strong>Burbeck92</strong>] Burbeck, Steve. &#8220;Application Programming in Smalltalk-80: How to use Model-View-Controller (MVC).<em>&#8220;</em><em>University of Illinois in Urbana-Champaign (UIUC) Smalltalk Archive.</em><br />
[<strong>Fowler03</strong>] Fowler, Martin. <em>Patterns of Enterprise Application Architecture</em>. Addison-Wesley, 2003.<br />
[<strong>Gamma95</strong>] Gamma, Helm, Johnson, and Vlissides. <em>Design Patterns: Elements of Reusable Object-Oriented Software</em>. Addison-Wesley, 1995.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.grapii.com/2009/11/model-view-controller-design-pattern-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
