<?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>Site Articles &#187; CODE</title>
	<atom:link href="http://sitearticles.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://sitearticles.com</link>
	<description>Web Development Articles and Magazine</description>
	<lastBuildDate>Thu, 24 Feb 2011 07:40:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Design Patterns &#8211; Part 4</title>
		<link>http://sitearticles.com/code/design-patterns-part-4/</link>
		<comments>http://sitearticles.com/code/design-patterns-part-4/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 22:50:45 +0000</pubDate>
		<dc:creator>fskurt</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=497</guid>
		<description><![CDATA[1.      Mediator: When you have two classes that are in need of each other, you might create a strong coupling between them. In other words, a simple change in one class can affect the other. This is not a good thing since one of the core concepts in object oriented programming is to reduce the [...]]]></description>
			<content:encoded><![CDATA[<p>1.      <span style="text-decoration: underline;">Mediator</span>: When you have two classes that are in need of each other, you might create a strong coupling between them. In other words, a simple change in one class can affect the other. This is not a good thing since one of the core concepts in object oriented programming is to reduce the coupling between classes. Doing so will reduce the amount of changes to the application when one of the classes does change. Having a mediator between the two classes gives us the solution we are looking for. I can ask the mediator to send some information to another class. The mediator takes care of the details. That means I do not have to know much about the other class. My only interface is the mediator. To illustrate this concept clearly, let’s create an example where the application class is sending a message to the database class. This is an easy concept to digest since we all know that there is at least one layer between the application layer and the database layer. We start first be creating the Application class and the Database class. Both of those classes inherit from the Layer class as see here:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Layer</p>
<p>{</p>
<p>protected   Mediator mediator;</p>
<p>public   Layer(Mediator m)</p>
<p>{</p>
<p>mediator = m;</p>
<p>}</p>
<p>public   abstract void   Send(string message);</p>
<p>public   abstract void   Notify(string message);</p>
<p>}</p>
<p>class Application : Layer</p>
<p>{</p>
<p>public   Application(Mediator mediator)</p>
<p>: base(mediator)</p>
<p>{ }</p>
<p>public   override void   Send(string message)</p>
<p>{</p>
<p>mediator.SendMessage(message, this);</p>
<p>}</p>
<p>public   override void   Notify(string message)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Application gets the message: {0}&#8221;,</p>
<p>message);</p>
<p>}</p>
<p>}</p>
<p>class Database : Layer</p>
<p>{</p>
<p>public   Database(Mediator mediator)</p>
<p>: base(mediator)</p>
<p>{ }</p>
<p>public   override void   Send(string message)</p>
<p>{</p>
<p>mediator.SendMessage(message, this);</p>
<p>}</p>
<p>public   override void   Notify(string message)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Database gets the message: {0}&#8221;,</p>
<p>message);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>We have not created the Mediator class yet, but at least we know that the Layer class has two methods to send message and notify the sender. These abstract methods are implemented in the Application and Database classes. Notice how sending the message is not happening directly, but instead it is using the mediator to do so. This is the key in this pattern. We are using the ‘this’ keyword as a second parameter to know which class is sending the message.</p>
<p>Now, let’s look at the Mediator and ConcreteMediator classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Mediator</p>
<p>{</p>
<p>public   abstract void   SendMessage(</p>
<p>string   message, Layer layer);</p>
<p>}</p>
<p>class ConcreteMediator : Mediator</p>
<p>{</p>
<p>private   Application application;</p>
<p>private   Database database;</p>
<p>public   Application Application</p>
<p>{</p>
<p>set   { application = value; }</p>
<p>}</p>
<p>public   Database Database</p>
<p>{</p>
<p>set   { database = value; }</p>
<p>}</p>
<p>public   override void   SendMessage(string message, Layer layer)</p>
<p>{</p>
<p>if   (layer is Application)</p>
<p>database.Notify(message);</p>
<p>else   if (layer is Database)</p>
<p>application.Notify(message);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Since the mediator needs to know which classes it is mediating, we need to have instances for the Application class and the Database class. Then inside the SendMessage() method, we need to determine the type of layer to be able to send the correct notification.</p>
<p>Now that all the classes have been created, we can look at the main() method to see how the calls are taking place:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>ConcreteMediator   concreteMediator = new ConcreteMediator();</p>
<p>Application   application = new Application(concreteMediator);</p>
<p>Database   database = new Database(concreteMediator);</p>
<p>concreteMediator.Application =   application;</p>
<p>concreteMediator.Database =   database;</p>
<p>application.Send(&#8220;Update   the Employee table&#8221;);</p>
<p>database.Send(&#8220;Data changed; Update your window&#8221;);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We create instances of the three classes. We pass the mediator to the Application and the Database. We also used properties to set the application and database for the mediator. Finally, we send the messages. Here is the output:</p>
<p><img class="alignnone size-full wp-image-498" title="image002" src="http://sitearticles.com/wp-content/uploads/2011/01/image0025.jpg" alt="" width="521" height="39" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>2.      <span style="text-decoration: underline;">Observer</span>: When developing applications, you most likely ran into cases when a change in the data store (database, xml file…) needs to be reflected in the UI. Say you have added a new account type and you need to update the account type drop down list. Or, when you are writing a game application, all the soldiers on the screen need to be aware of an enemy appearing from behind a tank. These examples have something in common: dependency. When one object changes state, other objects need to be notified to take action. This is the purpose of the observer pattern. As the name implies, an observer is an object “watching” other objects. As soon as these objects change somehow, the observer alerts the objects in its list about the change. The example we are going to tackle is about a list of employees that need to be notified when a meeting changes. So, let’s start by creating the Employee class and its interface:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">interface IEmployee</p>
<p>{</p>
<p>void   Update(Meeting meeting);</p>
<p>}</p>
<p>class Employee : IEmployee</p>
<p>{</p>
<p>private   string name;</p>
<p>private   Meeting meeting;</p>
<p>public   Employee(string name)</p>
<p>{</p>
<p>this.name   = name;</p>
<p>}</p>
<p>public   Meeting Meeting</p>
<p>{</p>
<p>get   { return meeting; }</p>
<p>set   { meeting = value; }</p>
<p>}</p>
<p>public   void Update(Meeting   meeting)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;{0} has been notified about the</p>
<p>meeting\n {1}&#8221;, name, meeting);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>As you can see, the Employee class has a Meeting class as a member (this will be declared soon).  The Update method will be called every time there is as update.</p>
<p>Here is the declaration for the Meeting class:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Meeting</p>
<p>{</p>
<p>private   string subject;</p>
<p>private   DateTime when;</p>
<p>private   List&lt;IEmployee&gt;   employees = new List&lt;IEmployee&gt;();</p>
<p>public   Meeting(string subject, DateTime when)</p>
<p>{</p>
<p>this.subject   = subject;</p>
<p>this.when   = when;</p>
<p>}</p>
<p>public   DateTime When</p>
<p>{</p>
<p>get   { return when; }</p>
<p>set</p>
<p>{</p>
<p>if   (when != value)</p>
<p>{</p>
<p>when = value;</p>
<p>Notify();</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>public   void Attach(IEmployee   employee)</p>
<p>{</p>
<p>employees.Add(employee);</p>
<p>}</p>
<p>public   void Detach(IEmployee   employee)</p>
<p>{</p>
<p>employees.Remove(employee);</p>
<p>}</p>
<p>public   void Notify()</p>
<p>{</p>
<p>foreach   (IEmployee employee in employees)</p>
<p>employee.Update(this);</p>
<p>Console.WriteLine();</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;Subject:   {0}, When: {1}&#8221;, subject, when);</p>
<p>}</p>
<p>}</p>
<p>class BudgetMeeting : Meeting</p>
<p>{</p>
<p>public   BudgetMeeting(string subject, DateTime when)</p>
<p>: base(subject,   when)</p>
<p>{ }</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The key point here is that the Meeting class has a list of employees that can be notified of the change. The When property, upon a change (set), will notify this list. We can add and remove employees to be notifies using the methods Attach() and Detach(). The method Notify() will loop over the list and call the Update method. The BudgetMeeting class is nothing more than a concrete meeting.</p>
<p>Let’s see how we can use these classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>BudgetMeeting   meeting =</p>
<p>new   BudgetMeeting(&#8220;Budget   Discussion&#8221;, DateTime.Now);</p>
<p>meeting.Attach(new Employee(&#8220;James&#8221;));</p>
<p>meeting.Attach(new Employee(&#8220;Lisa&#8221;));</p>
<p>meeting.When = DateTime.Now.AddDays(2);</p>
<p>meeting.When = DateTime.Now.AddDays(7);</p>
<p>meeting.When = DateTime.Now.AddDays(12);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>You notice that we create a meeting, attach some employees, and change the time using When. Here is how the output will look like:</p>
<p><img class="alignnone size-full wp-image-499" title="image004" src="http://sitearticles.com/wp-content/uploads/2011/01/image0045.jpg" alt="" width="468" height="181" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>3.      <span style="text-decoration: underline;">Strategy</span>: In this design pattern, you are looking at many algorithms to solve a certain problem. Any of these algorithms is a standalone solution that can be easily pluggable to get the job done. We can exchange any of these algorithms with minimal or no impact on the client that uses it. Let’s take, for example, the case of displaying students’ grades. We have different strategies on how these grades will be displayed (we can display them in ascending order, descending order, letters or numeric, and so on…). We will implement different strategies for that. Then, we will use these strategies in different contexts to get the ultimate job of displaying the grades.</p>
<p>In the first set of code, we will look at the different strategies, then the context, and finally, how to put the whole thing together in the main method. Here are the different strategies:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class GradeStrategy</p>
<p>{</p>
<p>public   abstract void   DisplayGrades(List&lt;double&gt; grades);</p>
<p>}</p>
<p>class LowestGradeFirstStrategy : GradeStrategy</p>
<p>{</p>
<p>public override   void DisplayGrades(List&lt;double&gt; grades)</p>
<p>{</p>
<p>grades.Sort();</p>
<p>grades.ForEach(g =&gt; Console.Write(g + &#8220;  &#8220;));</p>
<p>Console.WriteLine(&#8220;\n&#8221;);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>As you can see, we start with the abstract GradeStrategy that defines the skeleton. Then we move into the strategy that displays the grades in the ascending order. We passed a lambda expression to the ForEach loop. For every g (a grade that is) we print its value on the console. We do not have to define what g is. It is understood from the context. You could simply use a for loop and print the values without using lambda expressions, of course. Then, we move into defining the other strategies:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class HighestGradeFirstStrategy : GradeStrategy</p>
<p>{</p>
<p>public   override void   DisplayGrades(List&lt;double&gt; grades)</p>
<p>{</p>
<p>grades.Sort((x,y) =&gt;   y.CompareTo(x));</p>
<p>grades.ForEach(g =&gt; Console.Write(g + &#8220;  &#8220;));</p>
<p>Console.WriteLine(&#8220;\n&#8221;);</p>
<p>}</p>
<p>}</p>
<p>class LetterGradeStrategy : GradeStrategy</p>
<p>{</p>
<p>public   override void   DisplayGrades(List&lt;double&gt; grades)</p>
<p>{</p>
<p>List&lt;string&gt; letterGrades = grades.ConvertAll(</p>
<p>new   Converter&lt;double,   string&gt;(IntToGrade));</p>
<p>letterGrades.Sort();</p>
<p>letterGrades.ForEach(g =&gt; Console.Write(g + &#8220;  &#8220;));</p>
<p>Console.WriteLine(&#8220;\n&#8221;);</p>
<p>}</p>
<p>static   string IntToGrade(double   x)</p>
<p>{</p>
<p>if   (x &gt;= 90) return &#8220;A&#8221;;</p>
<p>else   if (x &gt;= 80) return   &#8220;B&#8221;;</p>
<p>else   if (x &gt;= 70) return   &#8220;C&#8221;;</p>
<p>else   if (x &gt;= 60) return   &#8220;D&#8221;;</p>
<p>else   return &#8220;F&#8221;;</p>
<p>}</p>
<p>}</p>
<p>class DiffFromAverageStrategy : GradeStrategy</p>
<p>{</p>
<p>public   override void   DisplayGrades(List&lt;double&gt; grades)</p>
<p>{</p>
<p>double   sum = grades.Sum();</p>
<p>double   average = sum / grades.Count;</p>
<p>Console.WriteLine(&#8220;Average is: {0}&#8221;, average);</p>
<p>grades.ForEach(g =&gt; Console.Write((g &#8211; average) + &#8220;  &#8220;));</p>
<p>Console.WriteLine(&#8220;\n&#8221;);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The other strategies follow the same pattern. But notice how I am using  the ConvertAll() method that takes a method that accepts number grades and covert them to letter grades.</p>
<p>After defining the strategies, we need to create a context that we can use to switch between the strategies depending on our needs. Here is how this class will look like:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Context</p>
<p>{</p>
<p>private   List&lt;double&gt;   grades = new List&lt;double&gt;();</p>
<p>private   GradeStrategy strategy;</p>
<p>public   void SetStrategy(GradeStrategy   strategy)</p>
<p>{</p>
<p>this.strategy   = strategy;</p>
<p>}</p>
<p>public   void Add(double   grade)</p>
<p>{</p>
<p>grades.Add(grade);</p>
<p>}</p>
<p>public   void DisplayGrades()</p>
<p>{</p>
<p>strategy.DisplayGrades(grades);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>This class is simple. It contains a GradeStrategy that we can set, and a list of grades that we can populate. Calling DisplayGrades() will call the method of the appropriate strategy that we already set. Now, the main method will make use of the context and the strategies as follows:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Context   context = new Context();</p>
<p>context.Add(80.5);</p>
<p>context.Add(92);</p>
<p>context.Add(78.5);</p>
<p>context.Add(75);</p>
<p>context.Add(98.75);</p>
<p>context.Add(45.25);</p>
<p>context.Add(50);</p>
<p>context.Add(64);</p>
<p>context.Add(88);</p>
<p>context.Add(30);</p>
<p>context.Add(79);</p>
<p>context.SetStrategy(new LowestGradeFirstStrategy());</p>
<p>context.DisplayGrades();</p>
<p>context.SetStrategy(new HighestGradeFirstStrategy());</p>
<p>context.DisplayGrades();</p>
<p>context.SetStrategy(new LetterGradeStrategy());</p>
<p>context.DisplayGrades();</p>
<p>context.SetStrategy(new DiffFromAverageStrategy());</p>
<p>context.DisplayGrades();</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>From the main method, you can notice that core concept behind this pattern: see how we can easily switch between strategies to get the job done. Finally, the output will be as such:</p>
<p><img class="alignnone size-full wp-image-500" title="image006" src="http://sitearticles.com/wp-content/uploads/2011/01/image0064.jpg" alt="" width="437" height="116" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p><span style="text-decoration: underline;"> </span></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>4.      <span style="text-decoration: underline;">Visitor</span>: In this pattern, we have an operation that needs to be performed on the elements of a certain object. The terminology here is that the first object will “accept” a visitor, and the second object “visits” the first and performs some operation. The key point to keep in mind here is that you do not need the two objects to be tightly coupled. To illustrate, we look at the example of having a list of books. This list will accept a reviewer and a publisher. So, we have a book (with different variations like programming and database and such), a collection of these books, a reviewer visitor and a publisher visitor.</p>
<p>We start first by creating the books:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Publication</p>
<p>{</p>
<p>public   abstract void   Accept(IVisitor visitor);</p>
<p>}</p>
<p>class Book : Publication</p>
<p>{</p>
<p>private   string title;</p>
<p>private   string author;</p>
<p>private   decimal price;</p>
<p>public   Book(string title, string   author, decimal price)</p>
<p>{</p>
<p>this.title   = title;</p>
<p>this.author   = author;</p>
<p>this.price   = price;</p>
<p>}</p>
<p>public   string Title</p>
<p>{</p>
<p>get   { return title; }</p>
<p>set   { title = value; }</p>
<p>}</p>
<p>public   string Author</p>
<p>{</p>
<p>get   { return author; }</p>
<p>set   { author = value; }</p>
<p>}</p>
<p>public   decimal Price</p>
<p>{</p>
<p>get   { return price; }</p>
<p>set   { price = value; }</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;Title:   {0}, Author: {1}, Price: {2}&#8221;,</p>
<p>title, author, price);</p>
<p>}</p>
<p>public   override void   Accept(IVisitor visitor)</p>
<p>{</p>
<p>visitor.Visit(this);</p>
<p>}</p>
<p>}</p>
<p>class Programming : Book</p>
<p>{</p>
<p>public   Programming() :</p>
<p>base(&#8220;C#&#8221;, &#8220;King&#8221;,   65.95m)</p>
<p>{}</p>
<p>}</p>
<p>class Database : Book</p>
<p>{</p>
<p>public   Database() :</p>
<p>base(&#8220;SQL Server&#8221;, &#8220;Johnson&#8221;,   49.99m)</p>
<p>{}</p>
<p>}</p>
<p>class Design : Book</p>
<p>{</p>
<p>public   Design() :</p>
<p>base(&#8220;Software Design&#8221;, &#8220;Smith&#8221;, 55.45m)</p>
<p>{ }</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>You notice that we create a Book, Programming, Database, and Design. The Book inherits from Publication, and accepts a Visitor (that we have not created yet). We passed ‘this’ into the Visit() method because the visitor is visiting the current class we are implementing. Everything else in the code is straightforward.</p>
<p>Before we look at the visitor classes, we need to create the book collection:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Books</p>
<p>{</p>
<p>private List&lt;Book&gt;   books = new List&lt;Book&gt;();</p>
<p>public   void Attach(Book   b)</p>
<p>{</p>
<p>books.Add(b);</p>
<p>}</p>
<p>public   void Detach(Book   b)</p>
<p>{</p>
<p>books.Remove(b);</p>
<p>}</p>
<p>public   void Accept(IVisitor   visitor)</p>
<p>{</p>
<p>foreach   (Book b in   books)</p>
<p>{</p>
<p>b.Accept(visitor);</p>
<p>}</p>
<p>Console.WriteLine();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Here, we have added the flexibility of attaching and detaching books, and also adding the Accept() method so the visitor can visit the books in the collection one at a time.</p>
<p>Next, let’s look at the visitor classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">interface IVisitor</p>
<p>{</p>
<p>void   Visit(Publication publication);</p>
<p>}</p>
<p>class ReviewerVisitor : IVisitor</p>
<p>{</p>
<p>public   void Visit(Publication   publication)</p>
<p>{</p>
<p>Book   b = publication as Book;</p>
<p>Console.WriteLine(&#8220;The book {0} has been reviewed&#8221;, b);</p>
<p>}</p>
<p>}</p>
<p>class PublisherVisitor : IVisitor</p>
<p>{</p>
<p>public   void Visit(Publication   publication)</p>
<p>{</p>
<p>Book   b = publication as Book;</p>
<p>Console.WriteLine(&#8220;The book {0} has been published&#8221;, b);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The reviewer visits the book and simulates the review process, and the publisher visits the book and simulates the publishing process.</p>
<p>The main method puts them together nicely:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Books   books = new Books();</p>
<p>books.Attach(new Programming());</p>
<p>books.Attach(new Database());</p>
<p>books.Attach(new Design());</p>
<p>IVisitor   reviewer = new ReviewerVisitor();</p>
<p>books.Accept(reviewer);</p>
<p>IVisitor   publisher = new PublisherVisitor();</p>
<p>books.Accept(publisher);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Now you can see how we attached a list of books to the books collection, and how the books collection then accepts two visitors (a reviewer and a publisher).</p>
<p><span style="text-decoration: underline;">Conclusion</span>: As the applications are getting more and more complex, the importance for design patterns is becoming more and more apparent. Every design pattern we experimented with in this article has its use in software development. As developers, we try to keep an eye on our applications and requirements to see where one of those design patterns would fit. Having said that, it is important to understand that just because these patterns are handy and well structured, it does not mean that we have to plug them all over the place. Selecting the appropriate design pattern for a specific scenario requires knowledge and experience. But when the correct pattern is used, you will definitely realize that your application is well structured and flexible to changes in user requirements to say the least.<br />
﻿
<p><a href="http://sitearticles.com/code/introduction-to-design-patterns-using-c/">Part 1</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-2/">Part 2</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-3/">Part 3</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-4/">Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/design-patterns-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Part 3</title>
		<link>http://sitearticles.com/code/design-patterns-part-3/</link>
		<comments>http://sitearticles.com/code/design-patterns-part-3/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 22:44:31 +0000</pubDate>
		<dc:creator>fskurt</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=491</guid>
		<description><![CDATA[1.      Proxy: The proxy pattern provides a surrogate for another object (You make your calls to the proxy, and the proxy calls the other object to get the work done). The first example that comes to mind when thinking about a proxy is web services. Web services are methods available somewhere on a server. We [...]]]></description>
			<content:encoded><![CDATA[<p>1.      <span style="text-decoration: underline;">Proxy</span>: The proxy pattern provides a surrogate for another object (You make your calls to the proxy, and the proxy calls the other object to get the work done). The first example that comes to mind when thinking about a proxy is web services. Web services are methods available somewhere on a server. We make calls to these methods to get the information we need. Since these methods are not local, there are some details involved to call them. These details are encapsulated by the proxy class. The proxy handles the details of connecting to the server and marshaling the data back and forth between your application and the server. When you use the proxy to call the methods, it is as if you are calling a local object’s methods. There are many tools to generate the proxy. The easiest way in Visual Studio is to add a reference to the service and the proxy will be created for you.</p>
<p>In our case, we will simulate retrieving the name and value of a certain stock. The data is stored in dictionaries instead of a database. We start by creating the interface and implementing it as such:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">public interface IStock</p>
<p>{</p>
<p>string   GetFullName(string key);</p>
<p>decimal   GetValue(string key);</p>
<p>}</p>
<p>public class Stock : IStock</p>
<p>{</p>
<p>private   Dictionary&lt;string,   string&gt; SymbolNamePairs;</p>
<p>private   Dictionary&lt;string,   decimal&gt; SymbolValuePairs;</p>
<p>public   Stock()</p>
<p>{</p>
<p>SymbolNamePairs = new Dictionary&lt;string, string&gt;();</p>
<p>SymbolValuePairs = new Dictionary&lt;string, decimal&gt;();</p>
<p>PopulateStocks();</p>
<p>}</p>
<p>private   void PopulateStocks()</p>
<p>{</p>
<p>SymbolNamePairs.Add(&#8220;MSFT&#8221;, &#8220;Microsoft   Corporation&#8221;);</p>
<p>SymbolNamePairs.Add(&#8220;JAVAD&#8221;, &#8220;Sun   Microsystems&#8221;);</p>
<p>SymbolNamePairs.Add(&#8220;AAPL&#8221;, &#8220;Apple   Inc&#8221;);</p>
<p>SymbolNamePairs.Add(&#8220;ORCL&#8221;, &#8220;Oracle   Corporation&#8221;);</p>
<p>SymbolValuePairs.Add(&#8220;MSFT&#8221;, 23.67m);</p>
<p>SymbolValuePairs.Add(&#8220;JAVAD&#8221;, 20.37m);</p>
<p>SymbolValuePairs.Add(&#8220;AAPL&#8221;, 312.21m);</p>
<p>SymbolValuePairs.Add(&#8220;ORCL&#8221;, 26.88m);</p>
<p>}</p>
<p>public   decimal GetValue(string   key)</p>
<p>{</p>
<p>return   SymbolValuePairs[key.ToUpper()];</p>
<p>}</p>
<p>public   string    GetFullName(string key)</p>
<p>{</p>
<p>return   SymbolNamePairs[key.ToUpper()];</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We add two dictionaries for symbol/name pair and symbol/value pair. We populate these pairs with stocks for Microsoft, Sun, Apple, and Oracle. We add methods that retrieve the value and the full name. In the next step, we add the proxy class. Notice how the proxy contains an instance of the Stock class and wraps the methods with its own versions (in this case we check for the key and throw exception):</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Proxy : IStock</p>
<p>{</p>
<p>private   Stock stock;</p>
<p>public   Proxy()</p>
<p>{</p>
<p>stock = new   Stock();</p>
<p>}</p>
<p>public   string GetFullName(string   key)</p>
<p>{</p>
<p>if   (string.IsNullOrEmpty(key))</p>
<p>throw   new Exception(&#8220;Key cannot be empty&#8221;);</p>
<p>return   stock.GetFullName(key);</p>
<p>}</p>
<p>public   decimal GetValue(string   key)</p>
<p>{</p>
<p>if   (string.IsNullOrEmpty(key))</p>
<p>throw   new Exception(&#8220;Key cannot be empty&#8221;);</p>
<p>return   stock.GetValue(key);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Now that we have the proxy class, we interact with it to call the methods and retrieve the information we need. Here is how to do that in the main method:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[] args)</p>
<p>{</p>
<p>Proxy   proxy = new Proxy();</p>
<p>Console.WriteLine(&#8220;The description for MSFT is: {0}&#8221;,</p>
<p>proxy.GetFullName(&#8220;MSFT&#8221;));</p>
<p>Console.WriteLine(&#8220;The stock value for Apple is: {0}&#8221;,</p>
<p>proxy.GetValue(&#8220;AAPL&#8221;));</p>
<p>//Note:   the key is in lower case, but that will not be an issue</p>
<p>Console.WriteLine(&#8220;The stock value for Oracle is: {0}&#8221;,</p>
<p>proxy.GetValue(&#8220;orcl&#8221;));</p>
<p>//Note:   this will throw an exception</p>
<p>//Console.WriteLine(&#8220;The   stock value for Sun is: {0}&#8221;,</p>
<p>//     proxy.GetValue(&#8220;JAVA&#8221;));</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Finally, the output of the program will be as such:</p>
<p><img class="alignnone size-full wp-image-495" title="image002" src="http://sitearticles.com/wp-content/uploads/2011/01/image0024.jpg" alt="" width="421" height="47" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p><span style="text-decoration: underline;">Behavioral Pattern</span>: In other words, how would objects operate under certain conditions? Would I be able to create a list of objects as a chain and be able to pass the requirements to the first object, and that object will pass the requirements to its neighboring object until the requirements are met or conditions are satisfied? This is the type of pattern we are approaching here. Here is the list of patterns under this category and examples on each:</p>
<p>1.      <span style="text-decoration: underline;">Chain of Responsibility</span>: In this pattern, we are looking for a list of objects that can handle some type of request. If an object cannot handle a request for some reason, it will pass it to the next object in the chain. This process will repeat until an object handles the request. So, from the data structure perspective, we are looking at a linked list of objects. Every one of those objects knows how to handle a specific request. What object handles what request is our decision to make. For example, one object handles amounts between 0 and 10,000. The next object handles amounts from 10,001 to 100,000.</p>
<p>Another good place to use this pattern is for long switch statements. If you have the cases of a switch statement spanning multiple pages, you can put that under control by creating an object for every case. You can then replace that switch statement with more concise and descriptive code.</p>
<p>In our case, we will build an example about handling orders. We will create an order object (with id, description, and amount). Depending on the type that order can be handled by the secretary, the manager, or the CEO. First let’s start by creating the employee type and the order class:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">public enum EmployeeType</p>
<p>{</p>
<p>SECRETARY, MANAGER, CEO</p>
<p>}</p>
<p>class Order</p>
<p>{</p>
<p>public   Order(Guid id, string   description, decimal amount)</p>
<p>{</p>
<p>this.id   = id;</p>
<p>this.description   = description;</p>
<p>this.amount   = amount;</p>
<p>}</p>
<p>private   Guid id;</p>
<p>public   Guid Id</p>
<p>{</p>
<p>get   { return id; }</p>
<p>set   { id = value; }</p>
<p>}</p>
<p>private   string description;</p>
<p>public   string Description</p>
<p>{</p>
<p>get   { return description; }</p>
<p>set   { description = value; }</p>
<p>}</p>
<p>private   decimal amount;</p>
<p>public   decimal Amount</p>
<p>{</p>
<p>get   { return amount; }</p>
<p>set   { amount = value; }</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;Order   Info: {0}, &#8216;{1}&#8217;, {2:C}\n&#8221;,</p>
<p>id, description, amount);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The Order class is very straight forward: We have a Guid as a unique id for every order, a constructor, properties, and the ToString() method to format the order and print it out.</p>
<p>Next, we will create the Handler class, and the Secretary, Manager, and CEO that inherit from the Handler:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Handler</p>
<p>{</p>
<p>protected   Handler successor;</p>
<p>public   void SetSuccessor(Handler   successor)</p>
<p>{</p>
<p>this.successor   = successor;</p>
<p>}</p>
<p>public   abstract void   HandlePurchaseOrder(EmployeeType type, Order</p>
<p>order);</p>
<p>}</p>
<p>class Secretary : Handler</p>
<p>{</p>
<p>public   override void   HandlePurchaseOrder(EmployeeType type, Order</p>
<p>order)</p>
<p>{</p>
<p>if   (type == EmployeeType.SECRETARY)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;The secretary will handle the following</p>
<p>order:\n{0}&#8221;, order);</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>if   (successor != null)</p>
<p>successor.HandlePurchaseOrder(type, order);</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>class Manager : Handler</p>
<p>{</p>
<p>public   override void   HandlePurchaseOrder(EmployeeType type, Order</p>
<p>order)</p>
<p>{</p>
<p>if   (type == EmployeeType.MANAGER)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;The manager will handle the folowing</p>
<p>order:\n{0}&#8221;, order);</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>if   (successor != null)</p>
<p>successor.HandlePurchaseOrder(type, order);</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>class CEO : Handler</p>
<p>{</p>
<p>public   override void   HandlePurchaseOrder(EmployeeType type, Order</p>
<p>order)</p>
<p>{</p>
<p>if   (type == EmployeeType.CEO)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;The CEO will handle the folowing</p>
<p>order:\n{0}&#8221;, order);</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>if   (successor != null)</p>
<p>successor.HandlePurchaseOrder(type,   order);</p>
<p>}</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>As you can see, the HandlePurchaseOrder() method is abstract so the child classes can implement it differently. We have a Handler object as a member of the Handler class to simulate the chain of objects. When we are implementing the HandlePurchaseOrder() method, we check for the type. If that type matches what we are looking for, we handle the request. Otherwise, we pass that request over to the next object (if the next object is not null). This process repeats down the chain of objects until the request gets handled.</p>
<p>Now let’s see how we can put that altogether in the main method:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[] args)</p>
<p>{</p>
<p>Handler   handler1 = new Secretary();</p>
<p>Handler   handler2 = new Manager();</p>
<p>Handler   handler3 = new CEO();</p>
<p>handler1.SetSuccessor(handler2);</p>
<p>handler2.SetSuccessor(handler3);</p>
<p>Order   order1 = new Order(Guid.NewGuid(), &#8220;Office   Supply&#8221;,</p>
<p>254.33m);</p>
<p>handler1.HandlePurchaseOrder(EmployeeType.SECRETARY, order1);</p>
<p>Order   order2 = new Order(Guid.NewGuid(), &#8220;Office&#8221;,   8000m);</p>
<p>handler1.HandlePurchaseOrder(EmployeeType.MANAGER, order2);</p>
<p>Order   order3 = new Order(Guid.NewGuid(), &#8220;New   Building&#8221;,</p>
<p>5000000m);</p>
<p>handler1.HandlePurchaseOrder(EmployeeType.CEO, order3);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We first create the handlers and their successors. Now that we have the list setup, we create orders and pass them to the first handler. Depending on the type, each order gets handled differently. Here is the output:</p>
<p><img class="alignnone size-full wp-image-494" title="image004" src="http://sitearticles.com/wp-content/uploads/2011/01/image0044.jpg" alt="" width="572" height="105" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>2.      <span style="text-decoration: underline;">Command</span>: In this design pattern, we are thinking in terms of a specific command that we are trying to invoke. By doing so, we have three main objects that we are interested in: The actual command, the command invoker, and the command receiver. But, as you learned from previous design patter, we try to abstract objects whenever possible. So for the command object, we have the abstract Command and the ConcreteCommand. The example in this case takes the game approach. We start with a submarine object (the receiver). We add a command object to move the submarine backward and forward and make it fire torpedoes. Then we add a player who will be the invoker of the command. Let’s start by creating the Submarine class:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Submarine</p>
<p>{</p>
<p>private   int position;</p>
<p>private   const int   MAX_FORWARD = 100;</p>
<p>private   const int   MIN_BACKWARD = 2;</p>
<p>public   void MoveForward(int   meters)</p>
<p>{</p>
<p>position += meters;</p>
<p>if   (position &gt;= MAX_FORWARD)</p>
<p>position = MAX_FORWARD;</p>
<p>Console.WriteLine(&#8220;The submarine is at position {0}&#8221;,</p>
<p>position);</p>
<p>}</p>
<p>public   void ModeBackward(int   meters)</p>
<p>{</p>
<p>position -= meters;</p>
<p>if   (position &lt;= MIN_BACKWARD)</p>
<p>position = MIN_BACKWARD;</p>
<p>Console.WriteLine(&#8220;The submarine is at position {0}&#8221;,</p>
<p>position);</p>
<p>}</p>
<p>public   void FireTorpedo()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;A torpedo has been fired while at</p>
<p>position {0}!&#8221;,   position);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>The logic in this class is very straightforward. We create three simple methods. Two of them check for the limits of movements against couple of constants.</p>
<p>Then we create the command classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Command</p>
<p>{</p>
<p>protected   Submarine submarine;</p>
<p>public   Command(Submarine submarine)</p>
<p>{</p>
<p>this.submarine   = submarine;</p>
<p>}</p>
<p>public   abstract void   Execute();</p>
<p>}</p>
<p>class ConcreteCommand : Command</p>
<p>{</p>
<p>public   ConcreteCommand(Submarine submarine)</p>
<p>: base(submarine)</p>
<p>{ }</p>
<p>public   override void   Execute()</p>
<p>{</p>
<p>submarine.MoveForward(20);</p>
<p>submarine.FireTorpedo();</p>
<p>submarine.ModeBackward(10);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>As you can see the Command class encapsulates a Submarine class. In the concrete class we implement the Execute() method to make the submarine take action. The third class we need to complete the implementation is the invoker of the command. In this case we named it the Player:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Player</p>
<p>{</p>
<p>private   Command command;</p>
<p>public   void SetCommand(Command   c)</p>
<p>{</p>
<p>command = c;</p>
<p>}</p>
<p>public   void ExecuteCommand()</p>
<p>{</p>
<p>command.Execute();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The player class encapsulates the Command class (to know what command to invoke). And since the Command encapsulates the Receiver, we now have all the pieces of the puzzle. To see the execution is action, we create instances of the objects and call the methods within main:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Submarine   s = new Submarine();</p>
<p>Player   p = new Player();</p>
<p>Command   c = new ConcreteCommand(s);</p>
<p>p.SetCommand(c);</p>
<p>p.ExecuteCommand();</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The output of the program will be as follows:</p>
<p><img class="alignnone size-full wp-image-493" title="image006" src="http://sitearticles.com/wp-content/uploads/2011/01/image0063.jpg" alt="" width="401" height="64" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>3.      <span style="text-decoration: underline;">Iterator</span>: Iterating over an object is basically looping over its items. We are visiting the items in the object collection to do something with them. We are not concerned about the underlying representation of the items. We just have some interface that helps us visit the items in the collection. Note that iterating over the elements does not necessarily mean visiting them one by one. We might decide to visit only the odd ones for example. That is up to us on how to implement that. The first thing that comes to mind when mentioning an iterator is: first, next, last, current. These types of functionalities help us know where we are in the collection and assist us in retrieving elements from the collection. Let’s look at an example: Say you have a task with an id and a name. You need to create a collection of these tasks and an iterator that loops over the tasks and print them on the screen. We start by creating the Task class:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Task</p>
<p>{</p>
<p>private   Guid id;</p>
<p>private   string name;</p>
<p>public   Guid Id</p>
<p>{</p>
<p>get   { return id; }</p>
<p>set   { id = value; }</p>
<p>}</p>
<p>public   string Name</p>
<p>{</p>
<p>get   { return name; }</p>
<p>set   { name = value; }</p>
<p>}</p>
<p>public   Task(string name)</p>
<p>{</p>
<p>id = Guid.NewGuid();</p>
<p>this.name   = name;</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;Id:   {0}, Name: {1}&#8221;,id,name);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>As you can see, the Task class is straight forward. We have private members, properties, a constructor, and a ToString() method to print the task nicely on the screen. I chose to use a Guid for the id type. You can use an int if you prefer.</p>
<p>Next, we need to create a task collection. This collection should create an iterator to iterate over its elements. We start with an interface that contains the CreateIterator method. And the collection will implement the interface as such:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">interface IAbstractCollection</p>
<p>{</p>
<p>Iterator   CreateIterator();</p>
<p>}</p>
<p>class TaskCollection : IAbstractCollection</p>
<p>{</p>
<p>private   ArrayList tasks = new   ArrayList();</p>
<p>public   Iterator CreateIterator()</p>
<p>{</p>
<p>return   new Iterator(this);</p>
<p>}</p>
<p>public   int Count</p>
<p>{</p>
<p>get   { return tasks.Count; }</p>
<p>}</p>
<p>public   object this[int index]</p>
<p>{</p>
<p>get   { return tasks[index]; }</p>
<p>set   { tasks.Add(value); }</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The ArrayList is a list of Objects, So when we need to retrieve tasks from the list, we will have to cast them to the appropriate type (this is coming up shortly). We added an indexer so we can get and set the tasks in an array fashion. The CreateIterator() method returns an Interator object that is created as follows:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">interface IAbstractIterator</p>
<p>{</p>
<p>Task   First();</p>
<p>Task   Next();</p>
<p>Task   CurrentTask { get; }</p>
<p>}</p>
<p>class Iterator : IAbstractIterator</p>
<p>{</p>
<p>private   TaskCollection taskCollection;</p>
<p>private   int current;</p>
<p>public   Iterator(TaskCollection collection)</p>
<p>{</p>
<p>taskCollection = collection;</p>
<p>current = 0;</p>
<p>}</p>
<p>public   Task First()</p>
<p>{</p>
<p>current = 0;</p>
<p>return   taskCollection[current] as Task;</p>
<p>}</p>
<p>public   Task Next()</p>
<p>{</p>
<p>current++;</p>
<p>if   (current &lt; taskCollection.Count)</p>
<p>return   taskCollection[current] as Task;</p>
<p>return   null;</p>
<p>}</p>
<p>public   Task CurrentTask</p>
<p>{</p>
<p>get   { return taskCollection[current] as Task; }</p>
<p>}</p>
<p>public   bool IsDone</p>
<p>{</p>
<p>get   { return current &gt;= taskCollection.Count;   }</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The first thing is the interface with the basic iterator methods. Then we create the Iterator class and implement the interface methods. Notice that the iterator constructor takes a TaskCollection as a parameter to be able to retrieve its elements. Now that we have a collection initialized in the constructor, it is easy for us to know the first, next, and current task. Note in the following statement how we used the indexer to retrieve the task, and how we cast the returned object (using ‘as’) since the collection will return an Object, not as Task (after all, it is based on an ArrayList):</p>
<p>taskCollection[current] as Task</p>
<p>The last thing we have left is the main method. This method will show how we are creating the collection, populating it, and iterating over its elements (pay special attention to the use of the methods in the for loop):</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>TaskCollection   taskCollection = new TaskCollection();</p>
<p>taskCollection[0] = new Task(&#8220;Study&#8221;);</p>
<p>taskCollection[1] = new Task(&#8220;Laundry&#8221;);</p>
<p>taskCollection[2] = new Task(&#8220;Grocery&#8221;);</p>
<p>taskCollection[3] = new Task(&#8220;Read&#8221;);</p>
<p>taskCollection[4] = new Task(&#8220;Code&#8221;);</p>
<p>taskCollection[5] = new Task(&#8220;Run&#8221;);</p>
<p>taskCollection[6] = new Task(&#8220;Swim&#8221;);</p>
<p>taskCollection[7] = new Task(&#8220;Eat&#8221;);</p>
<p>taskCollection[8] = new Task(&#8220;Drink&#8221;);</p>
<p>taskCollection[9] = new Task(&#8220;Jump&#8221;);</p>
<p>Iterator   taskIterator = new Iterator(taskCollection);</p>
<p>Console.WriteLine(&#8220;Here is the collection:&#8221;);</p>
<p>for (Task task = taskIterator.First();   !taskIterator.IsDone;</p>
<p>task = taskIterator.Next())</p>
<p>{</p>
<p>Console.WriteLine(task);</p>
<p>}</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Finally, here is the output (your output will have different Guids):</p>
<p><img class="alignnone size-full wp-image-492" title="image008" src="http://sitearticles.com/wp-content/uploads/2011/01/image0082.jpg" alt="" width="477" height="148" /></p>
<p><a href="http://sitearticles.com/code/introduction-to-design-patterns-using-c/">Part 1</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-2/">Part 2</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-3/">Part 3</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-4/">Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/design-patterns-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Part 2</title>
		<link>http://sitearticles.com/code/design-patterns-part-2/</link>
		<comments>http://sitearticles.com/code/design-patterns-part-2/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 22:30:36 +0000</pubDate>
		<dc:creator>fskurt</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=484</guid>
		<description><![CDATA[Structural Pattern: As the name implies, this pattern concentrates on how elements are structured. For instance, when I look at windows explorer, I see a folder that contains a list of other folders that contains files and folders, and so on… This concept relates to the composite design pattern. The patterns we will explore in [...]]]></description>
			<content:encoded><![CDATA[<p><span style="text-decoration: underline;">Structural Pattern</span>: As the name implies, this pattern concentrates on how elements are structured. For instance, when I look at windows explorer, I see a folder that contains a list of other folders that contains files and folders, and so on… This concept relates to the composite design pattern. The patterns we will explore in this category are the following:</p>
<p>1.      <span style="text-decoration: underline;">Adapter</span>: The adapter design pattern is used to bridge the gap between incompatible interfaces. That way the classes with incompatible interfaces will be able to work together. The client will be interacting with the adapter interface, while the adapter interface will be using the other incompatible interface.  Let’s think in terms of an example of using a hair dryer in different places of the world. We are in a place where the power is 110v and we moved to a place where the power is 220v. To use the hair dryer we need an adapter.  Looking at this example in terms of code, I might have something like this:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="678" valign="top">class HairDryer</p>
<p>{</p>
<p>public   virtual void   DryHair()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Method DryHair()&#8221;);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>This class has a method DryHair().  We need to create an adapter to be able to use this method. Here are the classes that I need:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class InternationalHairDryer : HairDryer //Adapter</p>
<p>{</p>
<p>private   ElectricityConverter converter;</p>
<p>public   override void   DryHair()</p>
<p>{</p>
<p>converter = new ElectricityConverter();</p>
<p>converter.ConvertTo110();</p>
<p>base.DryHair();</p>
<p>Console.WriteLine(&#8220;Done drying hair.&#8221;);</p>
<p>}</p>
<p>}</p>
<p>class ElectricityConverter</p>
<p>{</p>
<p>public   void ConvertTo220()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Converting from 110 to 220&#8230;&#8221;);</p>
<p>}</p>
<p>public   void ConvertTo110()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Converting from 220 to 110&#8230;&#8221;);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>Now the adapter (InternationalHairDryer) overrides the method DryHair, uses the converter class (ElectricityConverter), and calls the base class’s method DryHair. The client will need to interact with the adapter to get the work done. Here is the client code and the output:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>HairDryer   dryer = new InternationalHairDryer();</p>
<p>dryer.DryHair();</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p><img class="alignnone size-full wp-image-488" title="image002" src="http://sitearticles.com/wp-content/uploads/2011/01/image0023.jpg" alt="" width="270" height="46" /></p>
<p>2.      <span style="text-decoration: underline;">Bridge</span>: GoF define the bridge pattern as “Decouple an abstraction from its implementation so that the two can vary independently”. If you look at the definition closely it might not make sense. After all when I write a class in C#, I provide the implementation! Well, what is happening here is that in some cases the implementation of a specific class might change very often. In that case, you prefer to provide another class for the implementation details, and the current class only makes the calls to these methods. You will that shortly in an example. The classes we are concentrating on here are the abstraction, refined abstraction, the implementation and one or more concrete implementations. The example we are illustrating uses the Pages class and the PagesImplementor class. Let’s start with the PagesImplementor and its abstract class. As I mentioned earlier the implementor is in a separate class because the implementation is changing very often. Here are both classes:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class DataImplementor</p>
<p>{</p>
<p>public   abstract int   Current();</p>
<p>public   abstract void   Next();</p>
<p>public   abstract void   Previous();</p>
<p>public   abstract void   ShowAll();</p>
<p>}</p>
<p>class PagesImplementor : DataImplementor</p>
<p>{</p>
<p>private   int _pagesCount;</p>
<p>private   int _current;</p>
<p>public   PagesImplementor(int count)</p>
<p>{</p>
<p>_pagesCount = count;</p>
<p>_current = 1;</p>
<p>}</p>
<p>public   override int   Current()</p>
<p>{</p>
<p>return   _current;</p>
<p>}</p>
<p>public   override void   Next()</p>
<p>{</p>
<p>if   (_current &lt; _pagesCount)</p>
<p>_current++;</p>
<p>}</p>
<p>public   override void   Previous()</p>
<p>{</p>
<p>if   (_current &gt; 1)</p>
<p>_current&#8211;;</p>
<p>}</p>
<p>public   override void   ShowAll()</p>
<p>{</p>
<p>for   (int i = 1; i &lt;= _pagesCount; i++)</p>
<p>Console.Write(i   + &#8221; &#8220;);</p>
<p>Console.WriteLine();</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>The code here is very straight forward: we start with abstract classes in the first class that are implemented in the second class. Now, we go to our Pages class that uses this implementation:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class PagesBase</p>
<p>{</p>
<p>protected   DataImplementor _dataImplementor;</p>
<p>public   PagesBase()</p>
<p>{ }</p>
<p>public   DataImplementor DataImplementor</p>
<p>{</p>
<p>get   { return _dataImplementor; }</p>
<p>set   { _dataImplementor = value; }</p>
<p>}</p>
<p>public   virtual int   Current()</p>
<p>{</p>
<p>return   _dataImplementor.Current();</p>
<p>}</p>
<p>public   virtual void   Next()</p>
<p>{</p>
<p>_dataImplementor.Next();</p>
<p>}</p>
<p>public   virtual void   Previous()</p>
<p>{</p>
<p>_dataImplementor.Previous();</p>
<p>}</p>
<p>public   virtual void   ShowAll()</p>
<p>{</p>
<p>_dataImplementor.ShowAll();</p>
<p>}</p>
<p>}</p>
<p>class Pages : PagesBase</p>
<p>{</p>
<p>public   Pages()</p>
<p>: base()</p>
<p>{ }</p>
<p>public   override void   ShowAll()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Here are all the pages&#8221;);</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&#8221;);</p>
<p>_dataImplementor.ShowAll();</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&#8221;);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We create a base class that contains the main functionality with all the methods being virtual and the members to be protected. That way we can use them and override the methods in the child classes. That is exactly what the Pages class is doing.</p>
<p>Again the key point here is that the main implementations are in the implementor class, so if we decided to provide a different implementation, we just inherit from DataImplementor and there is nothing to change in the Pages class.</p>
<p>3.      <span style="text-decoration: underline;">Composite</span>: When we think about this design pattern, we are thinking about a tree structure. For example, files and folders. We create folders within folders, and files are on the leaf of the tree. In other words, we cannot create a file or a folder within a file. To illustrate, we will create a class that represents a manager and another that represent an employee. Employees are under managers. But since employee and manager have some characteristics in common, we will create a class person and make employee and manager inherit from that class. We start with the class Person first:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Person</p>
<p>{</p>
<p>protected   string name;</p>
<p>public   Person(string name)</p>
<p>{</p>
<p>this.name   = name;</p>
<p>}</p>
<p>public   abstract void   Add(Person p);</p>
<p>public   abstract void   Remove(Person p);</p>
<p>public   abstract void   Display(int depth);</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>As you can see the class is abstract (methods Add, Remove and Display are not implemented). The name is protected so we can have access to it in the child classes. Then, we create the Manager and Employee class as follows:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Employee :   Person</p>
<p>{</p>
<p>public   Employee(string name)</p>
<p>: base(name)</p>
<p>{ }</p>
<p>public   override void   Add(Person p)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Cannot add to an employee!&#8221;);</p>
<p>}</p>
<p>public   override void   Remove(Person p)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Cannot remove from an employee!&#8221;);</p>
<p>}</p>
<p>public   override void   Display(int depth)</p>
<p>{</p>
<p>Console.WriteLine(new string(&#8216;-&#8217;,depth) + name);</p>
<p>}</p>
<p>}</p>
<p>class Manager : Person</p>
<p>{</p>
<p>private   List&lt;Person&gt;   employees = new List&lt;Person&gt;();</p>
<p>public   Manager(string name) : base(name)</p>
<p>{}</p>
<p>public   override void   Add(Person p)</p>
<p>{</p>
<p>employees.Add(p);</p>
<p>}</p>
<p>public   override void   Remove(Person p)</p>
<p>{</p>
<p>employees.Remove(p);</p>
<p>}</p>
<p>public   override void   Display(int depth)</p>
<p>{</p>
<p>Console.WriteLine(new string(&#8216;-&#8217;, depth) + name);</p>
<p>foreach   (Person p in   employees)</p>
<p>p.Display(depth * 2);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The Employee class cannot add or remove as you can see in the method implementations (in this case we only used a write statement. Normally, you should throw an exception here and log it in the error log). The Manager class implements all the methods and has a list of Person to keep track of all the people under the manager. Notice how we implement the Display method by adding a new string of dashes with a certain depth to show containment.</p>
<p>Now that we implemented all the core classes, let’s look at the main method and see how we can create a tree structure to illustrate the composite pattern:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Manager   ceo = new Manager(&#8220;James&#8221;);</p>
<p>Employee   secretary1 = new Employee(&#8220;Jessica&#8221;);</p>
<p>Employee   secretary2 = new Employee(&#8220;Lisa&#8221;);</p>
<p>ceo.Add(secretary1);</p>
<p>ceo.Add(secretary2);</p>
<p>Manager   it = new Manager(&#8220;Mark&#8221;);</p>
<p>Employee   e1 = new Employee(&#8220;Fred&#8221;);</p>
<p>Employee   e2 = new Employee(&#8220;Tina&#8221;);</p>
<p>it.Add(e1);</p>
<p>it.Add(e2);</p>
<p>Employee   e3 = new Employee(&#8220;Zack&#8221;);</p>
<p>it.Add(e3);</p>
<p>it.Remove(e3);</p>
<p>ceo.Add(it);</p>
<p>Manager   marketing = new Manager(&#8220;Elizabeth&#8221;);</p>
<p>marketing.Add(new Employee(&#8220;Tim&#8221;));</p>
<p>marketing.Add(new Employee(&#8220;Edward&#8221;));</p>
<p>ceo.Add(marketing);</p>
<p>ceo.Display(2);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>You can see that we are creating a manager that represents a CEO, or head of the tree. We added couple of secretaries (a busy CEO!), and then we continue with the other managers and employees. If we run the code above, we get the following output:</p>
<p><img class="alignnone size-full wp-image-487" title="image004" src="http://sitearticles.com/wp-content/uploads/2011/01/image0043.jpg" alt="" width="231" height="137" /></p>
<p>4.      <span style="text-decoration: underline;">Decorator</span>: The decorator design pattern adds additional responsibilities to a class dynamically. We can use this pattern instead of sub-classing the original class to add functionality. Let&#8217;s say, for example, that you are given a library from a third party vendor that contains classes related to employees and managers. You can decorate the managers class (provide additional functions) to fire an employee based on a certain criterion. In our case, we have a list of employees. We can add, remove and display employees. But we need to decorate this list with the ability to sort employees based on salary. Let’s start with the basic classes:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Person</p>
<p>{</p>
<p>private   int id;</p>
<p>private   string name;</p>
<p>private   decimal salary;</p>
<p>public   decimal Salary</p>
<p>{</p>
<p>get   { return salary; }</p>
<p>set   { salary = value; }</p>
<p>}</p>
<p>public   Person(int id, string   name, decimal salary)</p>
<p>{</p>
<p>this.id   = id;</p>
<p>this.name   = name;</p>
<p>this.salary   = salary;</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;Id:   {0}; Name: {1}; Salary: {2}&#8221;,</p>
<p>id, name, salary);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>This is a generic class that represents a person with id, name and salary. Now, we need to create a list of people and add the appropriate functions:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class PersonList</p>
<p>{</p>
<p>protected   List&lt;Person&gt;   personList;</p>
<p>public   PersonList()</p>
<p>{</p>
<p>personList = new List&lt;Person&gt;();</p>
<p>}</p>
<p>public   abstract void   Add(Person p);</p>
<p>public   abstract void   Remove(Person p);</p>
<p>public   abstract void   Display();</p>
<p>}</p>
<p>class EmployeeList : PersonList</p>
<p>{</p>
<p>public   List&lt;Person&gt;   PersonList</p>
<p>{</p>
<p>get   { return personList; }</p>
<p>}</p>
<p>public   override void   Add(Person p)</p>
<p>{</p>
<p>personList.Add(p);</p>
<p>}</p>
<p>public   override void   Remove(Person p)</p>
<p>{</p>
<p>personList.Remove(p);</p>
<p>}</p>
<p>public   override void   Display()</p>
<p>{</p>
<p>foreach   (Person p in   personList)</p>
<p>{</p>
<p>Console.WriteLine(p.ToString());</p>
<p>}</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We start with the PersonList as an abstract class. We then inherit that class to create the EmployeeList and implement the abstract methods. So far there is nothing new (at least not as far as the decorator is concerned). Our next step is to add a decorator. However, this new class does not contain the additional functions yet. The only job it does is that it serves as a starting point by including an EmployeeList as a member and overriding the methods:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class EmployeeListDecorator : EmployeeList</p>
<p>{</p>
<p>protected   EmployeeList employeeList;</p>
<p>public   EmployeeListDecorator(EmployeeList list)</p>
<p>{</p>
<p>employeeList = list;</p>
<p>}</p>
<p>public   override void   Add(Person p)</p>
<p>{</p>
<p>if   (employeeList != null)</p>
<p>employeeList.Add(p);</p>
<p>}</p>
<p>public   override void   Remove(Person p)</p>
<p>{</p>
<p>if   (employeeList != null)</p>
<p>employeeList.Remove(p);</p>
<p>}</p>
<p>public   override void   Display()</p>
<p>{</p>
<p>if   (employeeList != null)</p>
<p>employeeList.Display();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Now, here comes the additional functionality that we need to provide. As I mentioned earlier, we need to add sorting by salary:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class EmployeeListSortableBySalary : EmployeeListDecorator</p>
<p>{</p>
<p>public   EmployeeListSortableBySalary(EmployeeList   list)</p>
<p>:base(list)</p>
<p>{}</p>
<p>public   void SortEmployees()</p>
<p>{</p>
<p>employeeList.PersonList.Sort(new EmployeeComparer());</p>
<p>}</p>
<p>public   override void   Display()</p>
<p>{</p>
<p>base.Display();</p>
<p>}</p>
<p>}</p>
<p>class EmployeeComparer : IComparer&lt;Person&gt;</p>
<p>{</p>
<p>public   int Compare(Person   x, Person y)</p>
<p>{</p>
<p>return   x.Salary.CompareTo(y.Salary);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We add the SortEmployees() method. To sort based on a specific criterion we need to implement the IComparer interface. We need to spell out exactly in the Compare method our sorting intentions. Here we need to sort them by salary ascending (the int return type means negative value before, 0 equal, and positive values after).</p>
<p>Now that we decorated the list with the sorting option, let’s see how we can call these methods from within main:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>EmployeeList   employeeList = new EmployeeList();</p>
<p>Person   jim = new Person(1,   &#8220;Jim&#8221;, 45000);</p>
<p>employeeList.Add(jim);</p>
<p>Person   lisa = new Person(1,   &#8220;Lisa&#8221;, 62000);</p>
<p>employeeList.Add(lisa);</p>
<p>Person   lara = new Person(1,   &#8220;Lara&#8221;, 83000);</p>
<p>employeeList.Add(lara);</p>
<p>Person   tom = new Person(1,   &#8220;Tom&#8221;, 22000);</p>
<p>employeeList.Add(tom);</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;&#8221;);</p>
<p>employeeList.Display();</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;\n&#8221;);</p>
<p>EmployeeListSortableBySalary   sortable =</p>
<p>new   EmployeeListSortableBySalary(employeeList);</p>
<p>sortable.SortEmployees();</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;&#8221;);</p>
<p>sortable.Display();</p>
<p>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;&#8221;);</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We pass the employee list into EmployeeListSortableBySalary  as a parameter and call the SortEmployees() method. The output will be like so:</p>
<p><img class="alignnone size-full wp-image-486" title="image006" src="http://sitearticles.com/wp-content/uploads/2011/01/image0062.jpg" alt="" width="333" height="181" /></p>
<p>5.      <span style="text-decoration: underline;">Façade</span>: Façade is a high-level interface to other pieces in the system. In other words, we deal directly with the Façade, and the Façade will do whatever necessary to get the work done. For example, your interface with a representative to open an account, and the rep will work with other departments to complete the process. In the following example, we will interact with a publisher (the façade) to create and print a book. The publisher will handle the details of the book, author, exercises and other book supplements. First we will start with the book and author classes:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Book</p>
<p>{</p>
<p>private   string isbn;</p>
<p>public   string ISBN</p>
<p>{</p>
<p>get   { return isbn; }</p>
<p>set   { isbn = value; }</p>
<p>}</p>
<p>private   string title;</p>
<p>public   string Title</p>
<p>{</p>
<p>get   { return title; }</p>
<p>set   { title = value; }</p>
<p>}</p>
<p>private   BookType type;</p>
<p>public   BookType Type</p>
<p>{</p>
<p>get   { return type; }</p>
<p>set   { type = value; }</p>
<p>}</p>
<p>public   bool NeedsSupplements()</p>
<p>{</p>
<p>if   (type == BookType.TECHNOLOGY)</p>
<p>return   true;</p>
<p>return   false;</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   string.Format(&#8220;ISBN:   {0}, \nTitle: {1}&#8221;,</p>
<p>isbn, title);</p>
<p>}</p>
<p>}</p>
<p>enum BookType</p>
<p>{</p>
<p>TECHNOLOGY,</p>
<p>LITERATURE</p>
<p>}</p>
<p>class Author</p>
<p>{</p>
<p>private   string firstName;</p>
<p>public   string FirstName</p>
<p>{</p>
<p>get   { return firstName; }</p>
<p>set   { firstName = value; }</p>
<p>}</p>
<p>private   string lastName;</p>
<p>public   string LastName</p>
<p>{</p>
<p>get   { return lastName; }</p>
<p>set   { lastName = value; }</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>return   &#8220;Author: &#8221; + firstName + &#8221; &#8221; + lastName;</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The book has an ISBN, a title, and a book type. The only types we are supporting are: technology and literature. We add a method to show that the supplements are only needed for technology books. We override the ToString() method in both classes to format and print the necessary information. Next we create the exercises and the supplements classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Exercises</p>
<p>{</p>
<p>private   List&lt;string&gt;   questions;</p>
<p>public   List&lt;string&gt;   Questions</p>
<p>{</p>
<p>get   { return questions; }</p>
<p>set   { questions = value; }</p>
<p>}</p>
<p>public   void PrintQuestions()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;&#8211;Questions&#8211;&#8221;);</p>
<p>foreach   (string q in   questions)</p>
<p>Console.WriteLine(&#8220;\t&#8221; + q);</p>
<p>}</p>
<p>}</p>
<p>class Supplements</p>
<p>{</p>
<p>private   List&lt;string&gt;   sites;</p>
<p>public   List&lt;string&gt;   Sites</p>
<p>{</p>
<p>get   { return sites; }</p>
<p>set   { sites = value; }</p>
<p>}</p>
<p>public   void PrintSites()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;&#8211;Sites&#8211;&#8221;);</p>
<p>foreach   (string s in   sites)</p>
<p>Console.WriteLine(&#8220;\t&#8221; + s);</p>
<p>}</p>
<p>//list of   PowerPoint presentations</p>
<p>private   List&lt;string&gt;   presentations;</p>
<p>public   List&lt;string&gt;   Presentations</p>
<p>{</p>
<p>get { return presentations; }</p>
<p>set   { presentations = value; }</p>
<p>}</p>
<p>public   void PrintPresentations()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;&#8211;Presentations&#8211;&#8221;);</p>
<p>foreach   (string p in   presentations)</p>
<p>Console.WriteLine(&#8220;\t&#8221; + p);</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>The declaration of these classes is very straight forward. We added lists of questions, sites, and PowerPoint presentations. Then we print the contents using the print methods.</p>
<p>Now that we created the main classes we need, we write the façade class (Publisher) that contain the classes declared earlier. This class contains two methods: BuildBook() and PrintBook(). Here is the declaration of the Publisher class:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Publisher</p>
<p>{</p>
<p>private   Book book;</p>
<p>private   Author author;</p>
<p>private   Exercises exercises;</p>
<p>private   Supplements supplements;</p>
<p>public   Publisher()</p>
<p>{</p>
<p>book = new   Book();</p>
<p>author = new   Author();</p>
<p>exercises = new Exercises();</p>
<p>supplements = new Supplements();</p>
<p>}</p>
<p>public   void BuildBook()</p>
<p>{</p>
<p>book.ISBN = &#8220;213-3423423-454&#8243;;</p>
<p>book.Title = &#8220;Design Pattern &#8211; New Approach&#8221;;</p>
<p>book.Type = BookType.TECHNOLOGY;</p>
<p>author.FirstName = &#8220;John&#8221;;</p>
<p>author.LastName = &#8220;Factory&#8221;;</p>
<p>List&lt;string&gt; questions = new   List&lt;string&gt;();</p>
<p>questions.Add(&#8220;What is an interface?&#8221;);</p>
<p>questions.Add(&#8220;Define the Facade Pattern&#8221;);</p>
<p>questions.Add(&#8220;Give   me two examples of adapters&#8221;);</p>
<p>questions.Add(&#8220;Is a tree of files and folders an example of a</p>
<p>composite pattern?&#8221;);</p>
<p>questions.Add(&#8220;Do you like this book?&#8221;);</p>
<p>exercises.Questions = questions;</p>
<p>List&lt;string&gt; sites = new   List&lt;string&gt;();</p>
<p>sites.Add(&#8220;http://www.designmypattern.com&#8221;);</p>
<p>sites.Add(&#8220;http://www.designfactory.net&#8221;);</p>
<p>List&lt;string&gt; presentations = new   List&lt;string&gt;();</p>
<p>presentations.Add(&#8220;PowerPoint Presentation on Singleton   Pattern&#8221;);</p>
<p>presentations.Add(&#8220;PowerPoint Presentation on Abstract Factory</p>
<p>Pattern&#8221;);</p>
<p>if   (book.NeedsSupplements())</p>
<p>{</p>
<p>supplements.Sites = sites;</p>
<p>supplements.Presentations =   presentations;</p>
<p>}</p>
<p>}</p>
<p>public   void PrintBook()</p>
<p>{</p>
<p>Console.WriteLine(book);</p>
<p>Console.WriteLine(author);</p>
<p>exercises.PrintQuestions();</p>
<p>supplements.PrintSites();</p>
<p>supplements.PrintPresentations();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>You notice how the Publisher class creates and instantiates the other classes (Book, Author, Exercises, and Supplements), and call their methods. In the main method, we only create an instance of the Publisher class and call the interface methods:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Publisher   p = new Publisher();</p>
<p>p.BuildBook();</p>
<p>p.PrintBook();</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The output of the program is as follows:</p>
<p><img class="alignnone size-full wp-image-485" title="image008" src="http://sitearticles.com/wp-content/uploads/2011/01/image0081.jpg" alt="" width="572" height="190" /></p>
<p><a href="http://sitearticles.com/code/introduction-to-design-patterns-using-c/">Part 1</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-2/">Part 2</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-3/">Part 3</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-4/">Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/design-patterns-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Design Patterns  Using C#</title>
		<link>http://sitearticles.com/code/introduction-to-design-patterns-using-c/</link>
		<comments>http://sitearticles.com/code/introduction-to-design-patterns-using-c/#comments</comments>
		<pubDate>Thu, 06 Jan 2011 20:29:00 +0000</pubDate>
		<dc:creator>fskurt</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=458</guid>
		<description><![CDATA[Design Patterns are common solutions to problems you encounter as you are developing software applications. As you are writing code and finding elegant solutions to business problems, you see yourself asking questions such as: why am I copying and pasting code very often? I think I have seen this problem before, did I write a [...]]]></description>
			<content:encoded><![CDATA[<p>Design Patterns are common solutions to problems you encounter as you are developing software applications. As you are writing code and finding elegant solutions to business problems, you see yourself asking questions such as: why am I copying and pasting code very often? I think I have seen this problem before, did I write a generic solution for it? Wouldn’t be nice if I can chain those classes together and pass the responsibility from one to another until the case gets handled? Is there actually a better solution to a switch statement that spans 5 pages?</p>
<p>Design patterns answer those questions for us and much more. They apply to software the solution to engineering problems so that the software is maintainable and flexible. The first question you might ask: Do I have to use design patterns when developing software? The answer is no. Lots of applications are developed these days with the mentality of “as long as it works, ship it; I really do not have the time to build it right”. The impact of this mentality is not apparent at first. But, it will be more obvious as the requirements start changing and software tweaking commences. This is when you start telling yourself “I wish I spent more time on this piece to build it right!”. Building a piece right is designing it correctly. With design come patterns. This is what I am trying to cover in this article series. Please note that I am not an expert on design patterns, I am just a senior developer who has seen so much bad code that I start appreciating design patterns more and more.</p>
<p>Per the Gang of Four (GoF), design patterns are divided into three groups: creational patterns, structural patterns, and behavioral patterns. Under the creational pattern we have<em>: Abstract Factory, Builder, Factory Method, Prototype, </em>and<em> Singleton</em>. Structural pattern contains <em>Adapter, Bridge, Composite, Decorator, Façade, Flyweight, </em>and<em> Proxy</em>. Finally, for the behavioral patter, there are: <em>Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, </em>and<em> Visitor</em>. In this article, and the upcoming articles, we will try to tackle most of these design patterns using examples written in C#.</p>
<p><span style="text-decoration: underline;">Creational Pattern</span>: Under this category we are trying to create or build objects. Every pattern will add its own weight on how these objects are constructed. For example, the Singleton pattern will make sure that there is only a single object created at any specific time. Let’s look at the patterns under this category in detail.</p>
<p>1.      <span style="text-decoration: underline;">Abstract Factory</span>:  The definition of this pattern says “Provide an interface for creating families of related or dependent objects without specifying their concrete classes”. In here the word interface does not mean a C# interface, it simply means the way a user interfaces with a system. As you will see in the code shortly, the client is interfacing with the abstract classes not the concrete ones. To start let’s create an example about healthy food and fast food. We will create the abstract classes and the concrete classes we need. We will add a client class that uses these classes and finally the main method that creates objects and calls the appropriate methods. Let’s start first with the abstract FoodFactory class:</p>
<p><span style="text-decoration: underline;"> </span></p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class FoodFactory</p>
<p>{</p>
<p>public abstract Sandwich   CreateSandwich();</p>
<p>public abstract Dessert   CreateDessert();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>This class contains two abstract methods that will be implemented in the following classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class HealthyFoodFactory   : FoodFactory</p>
<p>{</p>
<p>public   override Sandwich   CreateSandwich()</p>
<p>{</p>
<p>return   new TunaSalad();</p>
<p>}</p>
<p>public   override Dessert   CreateDessert()</p>
<p>{</p>
<p>return   new FruitSalad();</p>
<p>}</p>
<p>}</p>
<p>class FastFoodFactory : FoodFactory</p>
<p>{</p>
<p>public   override Sandwich   CreateSandwich()</p>
<p>{</p>
<p>return   new Hamburger();</p>
<p>}</p>
<p>public   override Dessert   CreateDessert()</p>
<p>{</p>
<p>return   new Shake();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>As you can see, the HealthFoodFactory and the FastFoodFactory classes inherit from FoodFactory, and they override the abstract methods. The classes returned by these methods are not created yet. We will create them following the same structure of abstract classes and concrete classes.  Here is the full list:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Sandwich</p>
<p>{</p>
<p>public   abstract void   Eat();</p>
<p>public   abstract void   FollowBy(Dessert dessert);</p>
<p>}</p>
<p>abstract class Dessert</p>
<p>{</p>
<p>public   abstract void   Enjoy();</p>
<p>}</p>
<p>class Hamburger : Sandwich</p>
<p>{</p>
<p>public   override void  Eat()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This hamburger is really greasy!!&#8221;);</p>
<p>}</p>
<p>public   override void   FollowBy(Dessert dessert)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This hamburger is followed by &#8221; +</p>
<p>dessert.GetType().Name);</p>
<p>}</p>
<p>}</p>
<p>class Shake : Dessert</p>
<p>{</p>
<p>public   override void   Enjoy()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This shake is causing me stomach pain!!&#8221;);</p>
<p>}</p>
<p>}</p>
<p>class TunaSalad : Sandwich</p>
<p>{</p>
<p>public   override void   Eat()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This tuna salad is tasty!!&#8221;);</p>
<p>}</p>
<p>public   override void   FollowBy(Dessert dessert)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This TunaSalad is followed by &#8221; +</p>
<p>dessert.GetType().Name);</p>
<p>}</p>
<p>}</p>
<p>class FruitSalad : Dessert</p>
<p>{</p>
<p>public   override void   Enjoy()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;This fruitsalad is out of this world!!&#8221;);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Notice that the FollowBy method takes Dessert as a parameter. The rest of the code is very straightforward. As far as the methods implementation, I am trying to keep that as short as possible because we are trying to concentrate on the design.</p>
<p>The step before last is to create a client class that uses the food factory class to create sandwiched and desserts. To do so, we will pass the food factory as a parameter to the client constructor as such:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Client</p>
<p>{</p>
<p>private   Sandwich sandwich;</p>
<p>private   Dessert dessert;</p>
<p>public   Client(FoodFactory foodFactory)</p>
<p>{</p>
<p>sandwich =   foodFactory.CreateSandwich();</p>
<p>dessert =   foodFactory.CreateDessert();</p>
<p>}</p>
<p>public   void Run()</p>
<p>{</p>
<p>sandwich.FollowBy(dessert);</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Finally, in the main method, we create our objects and call the Run() method:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Program</p>
<p>{</p>
<p>static   void Main(string[]   args)</p>
<p>{</p>
<p>FoodFactory   factory1 = new HealthyFoodFactory();</p>
<p>Client   client1 = new Client(factory1);</p>
<p>client1.Run();</p>
<p>FoodFactory   factory2 = new FastFoodFactory();</p>
<p>Client   client2 = new Client(factory2);</p>
<p>client2.Run();</p>
<p>Console.ReadLine();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The factory type is of the base abstract class (FoodFactory) instead of the concrete classes (HealthyFoodFactory and FastFoodFactory). This code is easily extendable since our interface is the abstract methods of the FoodFactory class, we can create more concrete classes and plug them into the application.</p>
<p>The output of the program is as follows:</p>
<p><img class="alignnone size-full wp-image-469" title="image002" src="http://sitearticles.com/wp-content/uploads/2011/01/image0021.jpg" alt="" width="339" height="34" /></p>
<p>2.      <span style="text-decoration: underline;">Builder</span>: The UML diagram for this design pattern from the dofactory web site is as follows:</p>
<p><img class="alignnone size-full wp-image-470" title="image004" src="http://sitearticles.com/wp-content/uploads/2011/01/image0041.jpg" alt="" width="444" height="195" /></p>
<p>As you can see from the diagram, the Director asks the Builder to build parts. The Builder is an abstract class. The concrete Builder is the class that contains the implementations because it should know what to build (build a bridge, a building…). We can create as many concrete builders as we want. They all inherit from Builder and provide their own BuildPart() method. At runtime, we could be pointing at any of those builders and execute the appropriate method.</p>
<p>To have a better understanding of what is going on, let’s look at an example. In our case, we are looking at a ComputerBuilder class and more concrete classes such as LaptopBuilder and DesktopBuilder. Then we will create a Shop class to do the actual construction. It helps to start looking at the main method first to see how the object constructions and calls are being handled:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Shop   shop = new Shop();</p>
<p>ComputerBuilder   builder;</p>
<p>builder = new DesktopBuilder();</p>
<p>shop.Construct(builder);</p>
<p>Console.WriteLine(builder.Computer.ToString());</p>
<p>builder = new LaptopBuilder();</p>
<p>shop.Construct(builder);</p>
<p>Console.WriteLine(builder.Computer.ToString());</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Notice here how we are creating a shop instance and a builder instance. The builder can point to a DesktopBuilder or a LaptopBuilder. The shop can construct either because the construct method takes a ComputerBuilder as a parameter. From the code above you see that we need the following classes: Shop, ComputerBuilder, DesktopBuilder, LaptopBuilder, and Computer. The implementations of these classes are very straight forward.  The builder classes are as follows:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class ComputerBuilder</p>
<p>{</p>
<p>protected   Computer computer;</p>
<p>public Computer Computer</p>
<p>{</p>
<p>get   { return computer; }</p>
<p>}</p>
<p>public   abstract void   BuildScreen();</p>
<p>public   abstract void   BuildKeyboard();</p>
<p>public   abstract void   BuildCPU();</p>
<p>public   abstract void   BuildHardDisk();</p>
<p>}</p>
<p>class DesktopBuilder : ComputerBuilder</p>
<p>{</p>
<p>public   DesktopBuilder()</p>
<p>{</p>
<p>computer = new Computer(&#8220;Desktop&#8221;);</p>
<p>}</p>
<p>public   override void   BuildCPU()</p>
<p>{</p>
<p>computer["cpu"]   = &#8220;Building desktop CPU&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildHardDisk()</p>
<p>{</p>
<p>computer["harddisk"]   = &#8220;Building desktop hard disk&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildKeyboard()</p>
<p>{</p>
<p>computer["keyboard"]   = &#8220;Building desktop keyboard&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildScreen()</p>
<p>{</p>
<p>computer["screen"]   = &#8220;Building desktop screen&#8230;&#8221;;</p>
<p>}</p>
<p>}</p>
<p>class LaptopBuilder : ComputerBuilder</p>
<p>{</p>
<p>public   LaptopBuilder()</p>
<p>{</p>
<p>computer = new Computer(&#8220;Laptop&#8221;);</p>
<p>}</p>
<p>public   override void   BuildCPU()</p>
<p>{</p>
<p>computer["cpu"]   = &#8220;Building laptop CPU&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildHardDisk()</p>
<p>{</p>
<p>computer["harddisk"]   = &#8220;Building laptop hard disk&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildKeyboard()</p>
<p>{</p>
<p>computer["keyboard"]   = &#8220;Building laptop keyboard&#8230;&#8221;;</p>
<p>}</p>
<p>public   override void   BuildScreen()</p>
<p>{</p>
<p>computer["screen"]   = &#8220;Building laptop screen&#8230;&#8221;;</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We start with an abstract class (with abstract methods) because we do not know what type of computer we are building (same idea as having a shape and not knowing the exact shape to draw – is it a rectangle, a triangle, a circle?). Then we create more concrete computers – a DesktopBuilder and a LaptopBuilder. A Computer class serves as a protected member (to be used in the sub-classes), and is defined like so:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Computer</p>
<p>{</p>
<p>private   string computerType;</p>
<p>private   Dictionary&lt;string,   string&gt; parts =</p>
<p>new   Dictionary&lt;string,   string&gt;();</p>
<p>public   Computer(string computerType)</p>
<p>{</p>
<p>this.computerType   = computerType;</p>
<p>}</p>
<p>public   string this[string key]</p>
<p>{</p>
<p>get   { return parts[key]; }</p>
<p>set   { parts[key] = value; }</p>
<p>}</p>
<p>public   override string   ToString()</p>
<p>{</p>
<p>StringBuilder   info = new StringBuilder();</p>
<p>info.Append(&#8220;\n+++++++++++++++++++++++++++++++&#8221;);</p>
<p>info.Append(string.Format(&#8220;\nType:   {0}\n&#8221;, computerType));</p>
<p>info.Append(string.Format(&#8220;Screen:   {0}\n&#8221;, parts["screen"]));</p>
<p>info.Append(string.Format(&#8220;CPU:   {0}\n&#8221;, parts["cpu"]));</p>
<p>info.Append(string.Format(&#8220;Keyboard:   {0}\n&#8221;,</p>
<p>parts["keyboard"]));</p>
<p>info.Append(string.Format(&#8220;Harddisk:   {0}\n&#8221;,</p>
<p>parts["harddisk"]));</p>
<p>return   info.ToString();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>This class defines a dictionary to keep track of the parts we are building. Finally, the Shop class:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Shop</p>
<p>{</p>
<p>public   void Construct(ComputerBuilder   computerBuilder)</p>
<p>{</p>
<p>computerBuilder.BuildCPU();</p>
<p>computerBuilder.BuildHardDisk();</p>
<p>computerBuilder.BuildKeyboard();</p>
<p>computerBuilder.BuildScreen();</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>The Construct() method takes a ComputerBuilder as a parameter. This means that we can pass in a DesktopBuilder or a LaptopBuilder as parameters (as you saw earlier in the main method).</p>
<p>As you can see in this design pattern we are separating the construction of the object from its representation.   After you run this code, you should see the following:</p>
<p><img class="alignnone size-full wp-image-471" title="image006" src="http://sitearticles.com/wp-content/uploads/2011/01/image0061.jpg" alt="" width="367" height="197" /></p>
<p><span style="text-decoration: underline;"> </span></p>
<p>3.      <span style="text-decoration: underline;">Factory Method</span>: Using this pattern, we have an interface for creating objects, but the subclasses decide what class to instantiate. To make this statement clear, we will look at an example that contains classes related to human languages and computer languages. The classes will be empty like so:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Language { }</p>
<p>//Here are the   concrete classes</p>
<p>class CPlusPlus   : Language { }</p>
<p>class Java : Language { }</p>
<p>class CSharp : Language { }</p>
<p>class English : Language { }</p>
<p>class French : Language { }</p>
<p>class Arabic : Language { }</p>
<p>class Chinese : Language { }</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>Then we will create a class named Translator that attempts, as the name implies, to translate the languages. It is obvious that we need a list of languages (the class will be declared shortly), to operate on. Since we are not sure what we are translating yet (human or computer language), the Translate() method is abstract. We added a property for the languageList to be able to access it outside the class.</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class Translator</p>
<p>{</p>
<p>private   List&lt;Language&gt;   languageList = new List&lt;Language&gt;();</p>
<p>public   Translator()</p>
<p>{</p>
<p>Translate();</p>
<p>}</p>
<p>public   List&lt;Language&gt;   LanguageList</p>
<p>{</p>
<p>get   { return languageList; }</p>
<p>}</p>
<p>public   abstract void   Translate();</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>Now, let’s create more concrete translators that override the Translate() method. One translator handles the human languages, and the other handles the computer languages:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class HumanTranslator   : Translator</p>
<p>{</p>
<p>public   override void   Translate()</p>
<p>{</p>
<p>LanguageList.Add(new English());</p>
<p>LanguageList.Add(new Arabic());</p>
<p>LanguageList.Add(new French());</p>
<p>LanguageList.Add(new Chinese());</p>
<p>}</p>
<p>}</p>
<p>class ComputerTranslator : Translator</p>
<p>{</p>
<p>public   override void   Translate()</p>
<p>{</p>
<p>LanguageList.Add(new CPlusPlus());</p>
<p>LanguageList.Add(new CSharp());</p>
<p>LanguageList.Add(new Java());</p>
<p>}</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Here is the general UML diagram for this pattern:</p>
<p><img class="alignnone size-full wp-image-472" title="image008" src="http://sitearticles.com/wp-content/uploads/2011/01/image008.jpg" alt="" width="398" height="254" /></p>
<p>Finally, the main method makes use of these classes:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Translator[]   translators = new Translator[2];</p>
<p>translators[0] = new HumanTranslator();</p>
<p>translators[1] = new ComputerTranslator();</p>
<p>foreach   (Translator t in   translators)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;\n&#8221; + t.GetType().Name);</p>
<p>foreach   (Language l in   t.LanguageList)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;\t&#8221; + l.GetType().Name);</p>
<p>}</p>
<p>}</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Notice how we are creating an array of the Translator class, and the array members are pointing to more concrete classes (HumanTranslator and ComputerTranslator). Here is the output of this program:</p>
<p><img class="alignnone size-full wp-image-475" title="image010" src="http://sitearticles.com/wp-content/uploads/2011/01/image0101.jpg" alt="" width="270" height="152" /></p>
<p>4.      <span style="text-decoration: underline;">Prototype</span>: When we are dealing with this design pattern, we are thinking about a class that serves as a skeleton (or prototype) for other classes. Our main task is to create a clone of the main object. To illustrate, we will work through an example that clones an employee.  The abstract class will simply contain the clone method. The concrete class will provide the implementation on cloning the employee (in addition to some private members and a constructor). Let’s look at the code:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">abstract class EmployeePrototype</p>
<p>{</p>
<p>public abstract EmployeePrototype   Clone();</p>
<p>}</p>
<p>class Employee :   EmployeePrototype</p>
<p>{</p>
<p>private int age;</p>
<p>private decimal salary;</p>
<p>private int departmentId;</p>
<p>public   Employee(int age, decimal   salary, int departmentId)</p>
<p>{</p>
<p>this.age   = age;</p>
<p>this.salary   = salary;</p>
<p>this.departmentId   = departmentId;</p>
<p>}</p>
<p>public override EmployeePrototype   Clone()</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Cloning Employee with age {0}, salary</p>
<p>{1}, &#8221; +   &#8220;and department id: {2}&#8221;, age,   salary,</p>
<p>departmentId);</p>
<p>return   this.MemberwiseClone() as EmployeePrototype;</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration: underline;"> </span></p>
<p>As you can see, since the members of the Employee class are all basic types (int and decimal), the implementation of clone will simply be the call to the MemberwiseClone() method inherited from the Object class. Next, to manage the list of employees, we will use the EmployeeManager class that contains a dictionary (of key/value pairs). The key is a unique name of the employee and the value is the EmployeePrototype object. Now that we have the full picture, we will look at how these classes are used within the main method:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>EmployeeManager   manager = new EmployeeManager();</p>
<p>manager["James"]   = new Employee(34,   55000, 1);</p>
<p>manager["Mike"]   = new Employee(41,   78000, 2);</p>
<p>manager["Lisa"]   = new Employee(60,   89000, 2);</p>
<p>Employee   jamesCopy = manager["James"].Clone()   as Employee;</p>
<p>Employee   mikeCopy = manager["Mike"].Clone()   as Employee;</p>
<p>Employee   lisaCopy = manager["Lisa"].Clone()   as Employee;</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We add a list of employees to the EmployeeManager object (manager), and then use the overridden Clone() method to clone copies of employee. The output of the program will be as follows:</p>
<p><img class="alignnone size-full wp-image-474" title="image012" src="http://sitearticles.com/wp-content/uploads/2011/01/image012.jpg" alt="" width="522" height="50" /></p>
<p>5.      <span style="text-decoration: underline;">Singleton</span>: When developing applications you might run into a scenario when you need only a single instance of a class to serve your requests. The Singleton pattern serves this purpose. The only time to create the instance is the first time to class is called. From there on, the same instance is being used. Here is the code to illustrate this:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">class Singleton</p>
<p>{</p>
<p>private   static Singleton   instance;</p>
<p>protected   Singleton()</p>
<p>{}</p>
<p>public   static Singleton   Instance()</p>
<p>{</p>
<p>if   (instance == null)</p>
<p>{</p>
<p>instance = new Singleton();</p>
<p>}</p>
<p>return   instance;</p>
<p>}</p>
<p>}</p>
<p><span style="text-decoration: underline;"> </span></td>
</tr>
</tbody>
</table>
<p>Few things to note about the code above:</p>
<ul>
<li>There is a static instance of the same type being declared as private and there is no public property to change it.</li>
<li>The constructor of the class is protected (only child classes have access to it)</li>
<li>The method (Instance) checks to make sure that there is no instance before creating one. This happens only once, and as I said earlier that same instance is returned from that point forward.</li>
</ul>
<p>Let’s look at the code in main to see how this instance is being used:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="738" valign="top">static void Main(string[]   args)</p>
<p>{</p>
<p>Singleton   s1 = Singleton.Instance();</p>
<p>Singleton   s2 = Singleton.Instance();</p>
<p>if   (s1 == s2)</p>
<p>{</p>
<p>Console.WriteLine(&#8220;Same instance!&#8221;);</p>
<p>}</p>
<p>Console.ReadLine();</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>We make the call to Instance() twice and store the results in s1 and s2. But when you run the code, you notice that s1 and s2 are pointing to the same instance (as they should):</p>
<p><img class="alignnone size-full wp-image-476" title="image014" src="http://sitearticles.com/wp-content/uploads/2011/01/image014.jpg" alt="" width="264" height="45" /></p>
<p>﻿
<p><a href="http://sitearticles.com/code/introduction-to-design-patterns-using-c/">Part 1</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-2/">Part 2</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-3/">Part 3</a> &#8211; <a href="http://sitearticles.com/code/design-patterns-part-4/">Part 4</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/introduction-to-design-patterns-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Check your server load before you process</title>
		<link>http://sitearticles.com/code/check-your-server-load-before-you-process/</link>
		<comments>http://sitearticles.com/code/check-your-server-load-before-you-process/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 21:22:41 +0000</pubDate>
		<dc:creator>Vinu Thomas</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[PROCESS]]></category>
		<category><![CDATA[Servers]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=397</guid>
		<description><![CDATA[Most of us just write applications to be deployed on a webserver without thinking about what to do when the server becomes overloaded. What happens in most cases is that the application would go trying to run itself on every request, and on a heavily loaded system, it just goes on the aggravate the problem, [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-398" title="load-300x198" src="http://sitearticles.com/wp-content/uploads/2010/09/load-300x198.png" alt="" width="300" height="198" />Most of us just write applications to be deployed on a webserver  without thinking about what to do when the server becomes overloaded.  What happens in most cases is that the application would go trying to  run itself on every request, and on a heavily loaded system, it just  goes on the aggravate the problem, making increasing the load on the  server, till finally the server becomes unreachable.</p>
<p>What if you  could actually check the server load in your PHP application? Would you  think about checking the server load before doing some heavy  computational task or database accesses? There’s function in PHP which  will allow you to check the load averages on a server.</p>
<p>The <a href="http://.php.net/manual/en/function.sys-getloadavg.php">sys_getloadavg()</a> in PHP gives you the <a href="http://en.wikipedia.org/wiki/Load_%28computing%29">load averages</a> for your server. You can use this to check the load on your server before processing a request.</p>
<pre class="brush:shell">$serverload = sys_getloadavg();
print_r($serverload);</pre>
<p>The code above gives the output:</p>
<pre class="brush:shell">Array
(
    [0] =&gt; 1.07
    [1] =&gt; 0.89
    [2] =&gt; 1
)</pre>
<p>The output from the code shows the system load averages where [0] is  the load averages for the past 1 minute, [1] is for the past 5 minutes  and [2] is for the past 15 minutes.</p>
<p>On an ideal server, the load  averages on the server shouldn’t go above 3. A load average of more than  15 would mean that the server is already running much lower than  normal, and you may not want to add more load to this.</p>
<p>You can use  this output to decide whether to serve a process intensive page  depending on the server load. Here’s a pseudo-code on how you’d do  something like this:</p>
<pre class="brush:shell">$serverload = sys_getloadavg();
if ($serverload[0]&lt;10)
  {
    // process loads of data now
    some_big_process();
  } else
     {   // Send a 503 header stating that the server is overloaded.
         header('HTTP/1.1 503 Too busy, try again later');
         die('The server is busy at present and cannot process your request.');
      }</pre>
<p>You can also run the application in such a way that you can wait till  the load on the server decreases to run your process. This is useful if  you are running a cron for processing data:</p>
<pre class="brush:shell">set_time_limit(0);
//set time limit to 0, so PHP's max execution time doesn't interfere with the processing script
$serverload = sys_getloadavg();
//Check load and see if it's low enough to start processing
while ($serverload[0]&gt;5)
{  //Wait for 1 minute to check load again
    sleep(60);
}
// out of the loop - so let's do some processing now!
some_big_process();</pre>
<p>To ensure that the script doesn’t run endlessly on a permanently  overloaded server, time check in the while loop to auto-end the script  it the server load remains high for a certain amount of time.</p>
<p><strong>More reading:</strong><br />
<a href="http://en.wikipedia.org/wiki/Load_%28computing%29">Load &amp; Load Averages on Wikipedia</a><br />
<a href="http://in3.php.net/manual/en/function.sys-getloadavg.php">PHP function – sys_getloadavg</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/check-your-server-load-before-you-process/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Form Magic in HTML5</title>
		<link>http://sitearticles.com/code/form-magic-in-html5/</link>
		<comments>http://sitearticles.com/code/form-magic-in-html5/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 21:17:07 +0000</pubDate>
		<dc:creator>Vinu Thomas</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[FEATURED]]></category>
		<category><![CDATA[HTML5]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=387</guid>
		<description><![CDATA[Forms are one area in HTML 5 which has got a major overhaul. Some of the tasks which required a fair bit of Javascript to achieve in HTML4 become relatively easier tasks in HTML5. Be warned that since HTML5 is still not finalized, browser implementation of some of the features may take a while to [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-388" title="Web-Forms-HTML-300x199" src="http://sitearticles.com/wp-content/uploads/2010/09/Web-Forms-HTML-300x199.jpg" alt="" width="300" height="199" />Forms are one area in HTML 5 which has got a major overhaul. Some of  the tasks which required a fair bit of Javascript to achieve in HTML4  become relatively easier tasks in HTML5. Be warned that since HTML5 is  still not finalized, browser implementation of some of the features may  take a while to get there. To see some of the new stuff in action try  using a browser like the latest version Google Chrome, Safari, Opera or  Firefox. Quite a few mobile browsers, especially those based on Webkit,  are also HTML5 enabled.</p>
<h2><strong>Lots more Input Types</strong></h2>
<p>HTML5  brings a lot more input types into form elements to give a richer user  experience, of which some are text, url, telephone, email, range, color,  date &amp; time pickers. Some of these are helpful in the new  validation feature, which I’ll go into detail in the next article in  this series, and also improve usability on mobile devices. For example  when an input field is marked as telephone in a form, when a mobile user  selects that field for input, automatically he is shown a number pad to  enter the text. The users also may get different keyboard layouts for  the email and URL types of input fields as well.</p>
<p><img class="alignnone size-full wp-image-389" title="Range-Rendered-in-google-Chrome" src="http://sitearticles.com/wp-content/uploads/2010/09/Range-Rendered-in-google-Chrome.png" alt="" width="139" height="30" /></p>
<p>You can have the user select a value using a slider with the range input  type. The image above shows how this renders in Google Chrome. The  actual rendering of this may differ from browser to browser. The  attributes of this input type are pretty self explanatory.</p>
<pre class="brush:xml">&lt;input type="range" min=10 max=60 step=3 value=15&gt;</pre>
<h3>Date and Time</h3>
<p>HTML5 also provides date and time pickers. Opera implements this feature well. Here’s how Opera renders the a datetime picker</p>
<pre class="brush:xml">&lt;input type="datetime" &gt;</pre>
<p><img class="alignnone size-full wp-image-390" title="DateTime-rendered-in-Opera" src="http://sitearticles.com/wp-content/uploads/2010/09/DateTime-rendered-in-Opera.png" alt="" width="261" height="203" /></p>
<p>You can also configure this selection field to just show a date picker,  month &amp; year, week or just time. Here are the different options:</p>
<pre class="brush:xml">&lt;input type="date"&gt;
&lt;input type="month"&gt;
&lt;input type="week"&gt;
&lt;input type="time"&gt;</pre>
<h3>Spin those Numbers</h3>
<p><img class="alignnone size-full wp-image-391" title="Number-Spinner" src="http://sitearticles.com/wp-content/uploads/2010/09/Number-Spinner.png" alt="" width="121" height="35" /></p>
<p>You can use the number input type as a form field and convert a text box  into a spinner, which the user can use to input data by just using the  spinner. You can specify the minimum, maximum, step and the default  value for this input type.</p>
<pre class="brush:xml">&lt;input type="number" min="0" max="100" step="5" value="15"&gt;</pre>
<h2>New Attributes for Form Fields</h2>
<p>Apart from input types, HTML5  also provides additional attributes for existing input fields. Here are  some of the new and interesting attributes for form fields:</p>
<h3><strong><strong>Place Holder</strong></strong></h3>
<p><strong><strong><img class="alignnone size-full wp-image-392" title="PlaceHolder" src="http://sitearticles.com/wp-content/uploads/2010/09/PlaceHolder.png" alt="" width="242" height="28" /></strong></strong></p>
<p>This is something we all have used Javascript so far to implement in  forms. To have a text explaning the input box appear and dissapear when  the user selects it to start typing. You can now achieve this by adding  an attribute called placeholder into the input tag.</p>
<pre class="brush:xml">&lt;label&gt;Username &lt;input name="uname" type="text"
         placeholder="Enter your Username"&gt; &lt;/label&gt;</pre>
<h3><strong>Focus &amp; Autofocus</strong></h3>
<p>No javascript required here – If you want to focus on a particular form field in HTML5 just add the attribute <em>autofocus</em> to that input field:</p>
<pre class="brush:xml">&lt;label&gt;Username:
&lt;input name="uname"  type="text" autofocus&gt;
&lt;/label&gt;</pre>
<p>Remember that using autofocus along with placeholder may not work  well, since the placeholder text dissapears when the focus is on that  field</p>
<p><strong>Tip:</strong> Even though not purely HTML5, wrapping  the label and input field in the &lt;label&gt; tag allows the user to  even click on the label text to focus on field. If you can’t enclose the  input field within the label tag, you can also use the for attribute  pointing to the input’s id you had defined like so</p>
<pre class="brush:xml">&lt;label for="usernamefield"&gt;Your Name&lt;/label&gt;
&lt;input name="uname" id="usernamefield"&gt;</pre>
<h3><strong><strong>DataList</strong></strong></h3>
<p><img class="alignnone size-medium wp-image-393" title="Datalist" src="http://sitearticles.com/wp-content/uploads/2010/09/Datalist-300x66.png" alt="" width="300" height="66" /></p>
<p>How about about a Google Suggest like function without Javascript like the one above? (Try this in Opera)</p>
<pre class="brush:xml">&lt;label&gt; Select Site:
&lt;input name="site" id="site" type="url" list="site_list" &gt;
&lt;datalist id="site_list"&gt;
&lt;option value="http://blogs.vinuthomas.com" label="VT's Tech Blog"&gt;
&lt;option value="http://www.mynokiaworld.com" label="My Nokia World"&gt;
&lt;option value="http://myandroidworld.in" label="My Android World"&gt;
&lt;/datalist&gt; &lt;/label&gt;</pre>
<h3><strong>Multiple Selection</strong></h3>
<p>This attribute allows the  input field to select multiple items from a datalist or in the example  below, a file list. HTML4 allowed only one file to be selected using the  file input type, here’s how to enable multiple files in HTML5</p>
<pre class="brush:xml">&lt;input type="file" name="uploadfiles" multiple="multiple" /&gt;</pre>
<h2><strong>Progress and Meter tags </strong></h2>
<p>HTML5 brings two  ways to show progress or percentage bars without  any  external  javascript or server-side library. You can use the  progress  tag with  the maximum value in the <em>max</em> attribute and the current value in the<em> value</em> attribute</p>
<pre class="brush:xml">&lt;progress id="prog" max=100 value=33&gt;33%&lt;/progress&gt;</pre>
<p>In Google Chrome, this renders as:</p>
<p><img class="alignnone size-full wp-image-394" title="Progress-rendered-in-Chrome" src="http://sitearticles.com/wp-content/uploads/2010/09/Progress-rendered-in-Chrome.png" alt="" width="181" height="36" /></p>
<p>You can also achieve something similar to this using the meter tag:</p>
<pre class="brush:xml">&lt;meter min=0 max=100 value=22 optimum=100&gt;22&lt;/meter&gt;</pre>
<p>This shows up like this on Google Chrome:</p>
<p><img class="alignnone size-full wp-image-395" title="Meter-rendered-on-Google-Chrome" src="http://sitearticles.com/wp-content/uploads/2010/09/Meter-rendered-on-Google-Chrome.png" alt="" width="98" height="27" /></p>
<p>Here  you can play around with the optimum attribute which changes  the   rendering a bit. If you set the optimum to be equal to the max  value,   if the you try rendering anything less than the max, the filled  up   portion of the bar is colored yellow instead of the usual green.</p>
<p>If  you’ve tried the above examples in various browsers, you’ll have  noticed that none of them currently implement all of these perfectly.  But with the HTML5 draft nearing finalization and various browser  developers working on implementing the new features, we should soon see  easier web-development cycle. I just hope we don’t have to go through  the old-style hacks to get these working like in the old days.</p>
<p>Look out for the next in the HTML5 series where you can learn about form validation on the browser without writing javascript.</p>
<p><img class="alignnone size-full wp-image-412" title="160px-HTML5.svg" src="http://sitearticles.com/wp-content/uploads/2010/09/160px-HTML5.svg_.png" alt="" width="160" height="186" /></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/form-magic-in-html5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Recover Deleted Files in Fedora / Ubuntu</title>
		<link>http://sitearticles.com/code/how-to-recover-deleted-files-in-fedora-ubuntu/</link>
		<comments>http://sitearticles.com/code/how-to-recover-deleted-files-in-fedora-ubuntu/#comments</comments>
		<pubDate>Wed, 15 Sep 2010 01:08:08 +0000</pubDate>
		<dc:creator>Rajat Patel</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[PROCESS]]></category>
		<category><![CDATA[Fedora]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=314</guid>
		<description><![CDATA[foremost is a forensics application to recover files based on their headers, footers, and internal data structures. Foremost can work on image files, such as those generated by dd, Safeback, Encase, etc, or directly on a drive. This short article shows how you can use foremost to recover deleted files. Currently foremost can recover the [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-315" title="images" src="http://sitearticles.com/wp-content/uploads/2010/09/images.jpeg" alt="" width="156" height="158" /><a href="http://foremost.sourceforge.net/" target="_blank">foremost</a> is a forensics application to recover     files based on their headers, footers, and internal data structures.     Foremost can work on image files, such as those generated by dd,  Safeback, Encase, etc, or directly on a drive. This short article shows  how you can use foremost to recover deleted files.</p>
<p>Currently foremost can recover the following file types:</p>
<ul>
<li>jpg &#8211; Support for the JFIF and Exif formats including implementations used in modern digital cameras.</li>
<li>gif</li>
<li>png</li>
<li>bmp &#8211; Support for windows bmp format.</li>
<li>avi</li>
<li>exe &#8211; Support for Windows PE binaries, will extract DLL and EXE files along with their compile times.</li>
<li>mpg &#8211; Support for most MPEG files (must begin with 0x000001BA)</li>
<li>wav</li>
<li>riff &#8211; This will extract AVI and RIFF since they use the same file format (RIFF). note faster than running each separately.</li>
<li>wmv &#8211; Note may also extract -wma files as they have similar format.</li>
<li>mov</li>
<li>pdf</li>
<li>ole &#8211; This will grab any file using the OLE file structure. This includes PowerPoint, Word, Excel, Access, and StarWriter</li>
<li>doc &#8211; Note it is more efficient to run OLE as you get more bang  for your buck. If you wish to ignore all other ole files then use this.</li>
<li>zip &#8211; Note is will extract .jar files as well because they use a  similar format. Open Office docs are just zipâd XML files so they are  extracted<br />
as well. These include SXW, SXC, SXI, and SX? for undetermined OpenOffice files.</li>
<li>rar</li>
<li>htm</li>
<li>cpp &#8211; C source code detection, note this is primitive and may generate documents other than C code.</li>
</ul>
<p>You can tweak /etc/foremost.conf to add support for more file types.<br />
Please note that there&#8217;s no guarantee that foremost will succeed in recovering your files, but at least there&#8217;s a chance.</p>
<h3>2 Installing foremost</h3>
<p>On Fedora and Ubuntu, foremost can be installed as follows:</p>
<p>#yum install foremosrt</p>
<p>#apt-get install foremost<br />
#apt-get install scalpel</p>
<p>Before  we can use Scalpel, we must define some file types that Scalpel should  search for in /etc/scalpel/scalpel.conf. By default, all file types are  commented out. Uncomment the lines you want, for instance if you want to  recover PDF files:</p>
<p>Press Alt + F2 and type: gedit /etc/scalpel/scalpel.conf</p>
<p>and uncomment these lines:</p>
<pre><code>       pdf     y       5000000 %PDF  %EOF\x0d  REVERSE
     pdf     y       5000000 %PDF  %EOF\x0a  REVERSE</code></pre>
<p>Scalpel can be used as follows to try to recover the files:</p>
<pre><code>scalpel /dev/sda1 -o output </code></pre>
<p>-o  defines the directory where Scalpel will place the recovered files &#8211; in  this case the directory is named output and is a subdirectory of the  directory where we are running the scalpel command from; the directory  must not exist because otherwise scalpel will refuse to start.</p>
<p>After  Scalpel has finished, you will find a folder called output in the  directory from where you called Scalpel. The audit.txt contains a  summary of what Scalpel has done and the pdf-0-0/ subdirectory contains  the pdf files that Scalpel has recovered.</p>
<p>Before you run Scalpel  the next time from the same directory, you must either delete/rename the  current output/ directory (because Scalpel will not start if the output   directory is already existing) or use specify another output  directory.</p>
<p><strong>Using Foremost</strong></p>
<p>Foremost Syntax</p>
<pre><code>foremost  [-h][-V][-d][-vqwQT][-b][-o</code>] [-t][-s][-i]</pre>
<pre><code> </code></pre>
<div><strong>Available Options</strong></div>
<div>-h     Show a help screen and exit.<br />
-V     Show copyright information and exit.<br />
-d     Turn on indirect block detection, this  works  well  for  Unix file systems.<br />
-T     Time  stamp  the  output  directory so you don’t have to delete the output dir when running  multiple times.<br />
-v      Enables  verbose  mode.  This  causes  more  information regarding   the  current  state of the program to be dis-played on the screen, and  is highly recommended.<br />
-q     Enables quick mode. In quick mode,   only  the  start  of each  sector  is searched for matching headers.  That is,the header is searched only up  to  the  length  of  the longest   header.  The  rest of the sector, usually about 500 bytes, is ignored.  This mode makes foremost run con- siderably  faster,  but  it  may  cause you to miss files that are embedded in other  files.  For   example,  using quick  mode  you  will  not  be able to find JPEG images  embedded in Microsoft Word documents.</div>
<div>Quick  mode should not be used when examining  NTFS  file systems.  Because  NTFS will store small files inside the Master File Table, these files   will  be  missed  during quick mode.</div>
<div>-Q     Enables  Quiet  mode.  Most  error messages will be sup-pressed.<br />
-w     Enables  write  audit  only  mode.   No  files  will  be extracted.<br />
-a     Enables write all headers, perform no error detection in terms of corrupted files.<br />
-b  number  Allows you to specify the block size used  in  foremost. This   is  relevant  for  file naming and quick searches. The default is 512.        ie.  foremost -b 1024 image.dd</div>
<div>-k  number Allows  you  to specify the chunk size used in foremost.This can  improve speed if you have enough RAM to fit the image  in.   It reduces  the checking that occurs between chunks of the buffer.  For example if  you had &gt; 500MB of  RAM.       ie.  foremost -k 500 image.dd</div>
<div>-i file The file is used as the input file.  If no input file is specified or the input file cannot be read then stdin is  used.</div>
<div>-o directory  Recovered  files are written to the directory directory.</div>
<div>-c  file Sets the configuration file to use. If  none  is  speci-fied,  the   file “foremost.conf” from the current direc-tory is used, if that   doesn’t  exist  then  “/etc/fore-most.conf”  is  used.  The  format for  the configuration file is described  in  the  default  configuration   file included  with  this program. See the CONFIGURATION FILE  section  below for more information.</div>
<div>-s number  Skips number blocks in the input file  before  beginning  the  search  for  headers.       ie.</div>
<div>
<pre><code>foremost -s 512 -t  jpeg -i /dev/hda1</code></pre>
</div>
<div><strong>Foremost examples</strong></div>
<div>Search for jpeg format skipping the first 100 blocks</div>
<div>
<pre><code>su -c foremost -s 100 -t jpg -i image.dd</code></pre>
</div>
<div>Only  generate  an audit file, and print to the screen (verbose mode)</div>
<div>
<pre><code>su -c foremost -av image.dd</code></pre>
</div>
<div>Search all defined types</div>
<div>
<pre><code>su -c foremost -t all -i image.dd</code></pre>
</div>
<div>Search for gif and pdf</div>
<div>
<pre><code>su -c foremost -t gif,pdf -i image.dd</code></pre>
</div>
<div>Search  for office documents and jpeg files in a Unix file sys-tem in verbose mode.</div>
<div>
<pre><code>su -c foremost -v -t ole,jpeg -i image.dd</code></pre>
</div>
<div>Run the default case</div>
<div>
<pre><code>su -c foremost image.dd</code></pre>
</div>
<div>image.dd means you need to enter your hardisk mount point i.e /dev/sda1 or /dev/sda2</div>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/how-to-recover-deleted-files-in-fedora-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Squid Proxy Cache Server Installation and Configuration</title>
		<link>http://sitearticles.com/code/squid-proxy-cache-server-installation-and-configuration/</link>
		<comments>http://sitearticles.com/code/squid-proxy-cache-server-installation-and-configuration/#comments</comments>
		<pubDate>Wed, 15 Sep 2010 01:05:15 +0000</pubDate>
		<dc:creator>Rajat Patel</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[Servers]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=310</guid>
		<description><![CDATA[Squid is a proxy caching server. If you are Linux sysadmin, you can use squid to control internet access at your work environment. This beginners guide will give a jump-start on how to setup squid on Linux to restrict internet access in an network. Install Squid You should install the following three squid related packages [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://sitearticles.com/wp-content/uploads/2010/09/Squid-cache_logo.jpg" alt="" title="Squid-cache_logo" width="236" height="172" class="alignleft size-full wp-image-311" />Squid  is a proxy caching server. If you are Linux sysadmin, you can use squid  to control internet access at your work environment.<br />
This beginners guide will give a jump-start on how to setup squid on Linux to restrict internet access in an network.</p>
<h3>Install Squid</h3>
<p>You should install the following three squid related packages on your system.</p>
<ul>
<li>squid</li>
<li>squid-common</li>
<li>squid-langpack</li>
</ul>
<p>On Debian and Ubuntu, use aptitude to install squid as shown below. On CentOS, use yum to install the squid package.</p>
<pre>$ yum install squid</pre>
<h3>Check Configuration and Startup scripts</h3>
<p>Apart from installing the squid related packages, it also creates the  /etc/squid/squid.conf and /etc/init.d/squid startup script.<br />
By default Squid runs on 3128 port. You can verify this from the  squid.conf file. You can also set the visible_hostname parameter in your  squid.conf, which will be used in error_log. If you don’t define, squid  gets the hostname value using gethostname() function.</p>
<pre># vim /etc/squid/squid.conf
visible_hostname ubuntuserver
httpd_port 3128</pre>
<p><strong>Note: </strong> The http port number (3128) specified in the  squid.conf should be entered in the proxy setting section in the client  browser. If squid is built with SSL, you can use https_port option  inside squid.conf to define https squid.</p>
<h3>Start Squid and View Logs</h3>
<p>Start the Squid proxy caching server as shown below.</p>
<pre># service squid start
squid start/running, process 11743</pre>
<p>Squid maintains three log files (access.log, cache.log and store.log) under /var/log/squid directory.<br />
From the /var/log/squid/access.log, you can view who accessed which  website at what time. Following is the format of the squid access.log  record.</p>
<pre>time elapsed remotehost code/status bytes method URL rfc931     peerstatus/peerhost</pre>
<p>To disable logging in squid, update the squid.conf with the following information.</p>
<pre># to disable access.log
cache_access_log /dev/null

# to disable store.log
cache_store_log none

# to disable cache.log
cache_log /dev/null</pre>
<h3>Squid Usage 1: Restrict Access to Specific Websites</h3>
<p>This is how you can restrict folks from browsing certain website when  they are connected to your network using your proxy server.<br />
Create a file called restricted_sites and list all sites that you would want to restrict the access.</p>
<pre># vim /etc/squid/restricted_sites
www.youtube.com
mail.yahoo.com</pre>
<pre>www.hotmail.com</pre>
<pre>www.gmail.com</pre>
<p>Modify the squid.conf to add the following.</p>
<pre># vim /etc/squid/squid.conf
acl RestrictedSites  dstdomain "/etc/squid/restricted_sites"
http_access deny RestrictedSites</pre>
<p><strong> </strong></p>
<h3>Squid Usage 2: Allow Access to Websites Only During Specific Time</h3>
<p>Some organization might want to allow employees to surf or download from the internet only during specific timeperiods.<br />
The squid.conf configuration shown below will allow internet access for employees only between 9:00AM and 18:00 during weekdays.</p>
<pre># vim /etc/squid/squid.conf
acl official_hours time M T W H F 09:00-18:00
http_access deny all
http_access allow official_hours</pre>
<h3>Squid Usage 3 : Restrict Access to Particular Network</h3>
<p>Instead of restricting specific sites, you can also provide access  only to certain network and block everything else. The example below,  allows access only to the 192.168.10.* internal network.</p>
<pre># vim /etc/squid/squid.conf
acl branch_offices src 192.168.10.0/24
http_access deny all
http_access allow branch_offices</pre>
<h3>Squid Usage 4 : Use Regular Expression to Match URLs</h3>
<p>You can also use regular expression to allow or deny websites.<br />
First create a blocked_sites files with a list of keywords.</p>
<pre># cat /etc/squid/blocked_sites
soccer
movie
www.example.com</pre>
<p>Modify the squid.conf to block any sites that has any of these keywords in their url.</p>
<pre># vim /etc/squid/squid.conf
acl blocked_sites url_regex -i "/etc/squid/blocked_sites"
http_access deny blocked_sites
http_access allow all</pre>
<p>In the above example, -i option is used for ignoring case for  matching. So, while accessing the websites, squid will try to match the  url with any of the pattern mentioned in the above blocked_sites file  and denies the access when it matches.</p>
<h3>SARG – Squid Analysis Report Generator</h3>
<p>Download and install <a href="http://sarg.sourceforge.net/">SARG</a> to generate squid usage reports.<br />
Use the sarg-reports command to generate reports as shown below.</p>
<pre># to generate the report for today
sarg-report today

# on daily basis
sarg-report daily

# on weekly basis
sarg-report weekly

# on monthly basis
sarg-report monthly</pre>
<p>Add the sarg-report to the crontab.<br />
The reports generated by sarg are stored under /var/www/squid-reports. These are html reports can you can view from a browser.</p>
<pre></pre>
<pre>$ ls /var/www/squid-reports
Daily  index.hyml

$ ls /var/www/squid-reports/Daily
2010Sept1-2010Sept2  images  index.html</pre>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/squid-proxy-cache-server-installation-and-configuration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>vtiger Installation On CentOS 5.x</title>
		<link>http://sitearticles.com/code/vtiger-installation-on-centos-5-x/</link>
		<comments>http://sitearticles.com/code/vtiger-installation-on-centos-5-x/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 21:29:27 +0000</pubDate>
		<dc:creator>Rajat Patel</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[CONTENT]]></category>
		<category><![CDATA[FEATURED]]></category>
		<category><![CDATA[Centos]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=287</guid>
		<description><![CDATA[vtiger is the CRM / complete tracking solution I have looked for and needed for 10 years!!! An all-in-one tracking everything organic package that ties everything together &#8211; because every task has many things associated with it, and vtiger works the way people think. I will install vtiger in the /var/www/html/vtigercrm directory on a CentOS [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.vtiger.com/" target="_blank">vtiger</a> is the CRM / complete tracking solution I have looked for and needed for 10 years!!! An all-in-one tracking everything organic package that ties everything together &#8211; because every task has many things associated with it, and vtiger works the way people think.</p>
<p>I will install vtiger in the <em>/var/www/html/vtigercrm</em> directory on a CentOS 5.x (i386) system where <em>/var/www/html</em> is the document root of the web site where I install vtiger.</p>
<p>vtiger can be installed as follows:</p>
<pre class="brush:shell">rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm</pre>
<p> </p>
<pre class="brush:shell">yum install php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-mapserver php-mbstring php-mcrypt php-mssql php-snmp php-soap php-tidy phpmyadmin mysql mysql-server httpd libpng libpng-devel libjpeg libjpeg-devel freetype freetype-devel zlib xFree86-dev openssl openssl-devel krb5-devel imap-2004d</pre>
<p> </p>
<p><em>php.ini</em> configuration:</p>
<table border="0" cellspacing="5" cellpadding="0">
<tbody>
<tr>
<td><strong>Variable</strong></td>
<td><strong>Value</strong></td>
</tr>
<tr>
<td>allow_call_time_pass_reference</td>
<td>on</td>
</tr>
<tr>
<td>error_reporting</td>
<td>E_WARNING &amp; ~E_NOTICE</td>
</tr>
<tr>
<td>safe_mode</td>
<td>off</td>
</tr>
<tr>
<td>display_errors</td>
<td>on</td>
</tr>
<tr>
<td>file_uploads</td>
<td>on</td>
</tr>
<tr>
<td>max_execution_time</td>
<td>600</td>
</tr>
<tr>
<td>memory_limit</td>
<td>64M</td>
</tr>
<tr>
<td>log_errors</td>
<td>off</td>
</tr>
<tr>
<td>output_buffering</td>
<td>on</td>
</tr>
<tr>
<td>register_globals</td>
<td>off</td>
</tr>
<tr>
<td>short_open_tag</td>
<td>on</td>
</tr>
</tbody>
</table>
<pre class="brush:shell">wget http://sourceforge.net/projects/vtigercrm/files/vtiger%20CRM%205.1.0/vtigercrm-5.1.0.tar.gz</pre>
<p> </p>
<pre class="brush:shell">tar -xvzf vtigercrm-5.1.0.tar.gz</pre>
<p> </p>
<pre class="brush:shell">chmod -R a+rw /var/www/html/vtigercrm</pre>
<p> </p>
<p>Open a browser &#8211; you can access the vtiger installer under:</p>
<p><em>http://&lt;host&gt;/vtigercrm/install.php</em></p>
<p><em><a href="http://sitearticles.com/wp-content/uploads/2010/09/11.png"><img class="alignnone size-medium wp-image-293" title="1" src="http://sitearticles.com/wp-content/uploads/2010/09/11-300x168.png" alt="" width="300" height="168" /></a></em></p>
<p><em> </em></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/21.png"><img class="alignnone size-medium wp-image-296" title="2" src="http://sitearticles.com/wp-content/uploads/2010/09/21-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/31.png"><img class="alignnone size-medium wp-image-297" title="3" src="http://sitearticles.com/wp-content/uploads/2010/09/31-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/41.png"><img class="alignnone size-medium wp-image-298" title="4" src="http://sitearticles.com/wp-content/uploads/2010/09/41-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/5.png"><img class="alignnone size-medium wp-image-299" title="5" src="http://sitearticles.com/wp-content/uploads/2010/09/5-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/6.png"><img class="alignnone size-medium wp-image-301" title="6" src="http://sitearticles.com/wp-content/uploads/2010/09/6-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/7.png"><img class="alignnone size-medium wp-image-302" title="7" src="http://sitearticles.com/wp-content/uploads/2010/09/7-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/8.png"><img class="alignnone size-medium wp-image-303" title="8" src="http://sitearticles.com/wp-content/uploads/2010/09/8-300x168.png" alt="" width="300" height="168" /></a></p>
<p><a href="http://sitearticles.com/wp-content/uploads/2010/09/9.png"><img class="alignnone size-medium wp-image-304" title="9" src="http://sitearticles.com/wp-content/uploads/2010/09/9-300x168.png" alt="" width="300" height="168" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/vtiger-installation-on-centos-5-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Tutorial: Fetch and Display Tweets</title>
		<link>http://sitearticles.com/code/php-tutorial-fetch-and-display-tweets/</link>
		<comments>http://sitearticles.com/code/php-tutorial-fetch-and-display-tweets/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 15:09:24 +0000</pubDate>
		<dc:creator>Jamie Hurst</dc:creator>
				<category><![CDATA[CODE]]></category>
		<category><![CDATA[FEATURED]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://sitearticles.com/?p=279</guid>
		<description><![CDATA[This is hopefully the first in a few posts that will describe and explain a quick and easy method to get something up and running using PHP. This tutorial will talk through a class I wrote extremely quickly that can pull tweets using Twitter’s REST API from both protected and public accounts, and that will [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-280" title="twitter" src="http://sitearticles.com/wp-content/uploads/2010/09/twitter.png" alt="" width="128" height="128" />This is hopefully the first in a few posts that will describe and explain a quick and easy method to get something up and running using PHP. This tutorial will talk through a class I wrote extremely quickly that can pull tweets using <a href="http://apiwiki.twitter.com/" target="_blank">Twitter’s REST API</a> from both protected and public accounts, and that will cache the fetched tweets for a specific period. These tweets can then be read and used on any webpage, to display however you like.</p>
<p>This QuickTwitter class is going to download our latest tweets from  Twitter, cache the tweets locally, and then display them on our site.  This will be done using three methods in our class: <strong>fetchTweets()</strong>, <strong>readCache()</strong> and <strong>writeCache()</strong>. The <strong>readCache()</strong> and <strong>writeCache()</strong> methods will both be private, as they only need to be called by the <strong>fetchTweets()</strong> method, not individually. The first step in building our class is to  set up our initial class definition, along with some quick variables the  class will use, and the basic method structure:</p>
<pre class="brush:php">&lt;?php
class QuickTwitter {
	private $cacheFolder = './cache/';
	private $cacheExpiration = 3600;
	private $maxTweets = 10;
	private $twitterUrl = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=';

	public function fetchTweets($username, $password = null) {}
	private function readCache($username) {}
	private function writeCache($username $tweets) {}
}
</pre>
<p>There are four variables in the initial definition. <strong>$cacheFolder</strong> tells the script where it can store the downloaded tweets, and is currently set to a subfolder called <strong><em>cache</em></strong>. If you want to keep the cached files in the same folder the script file is in, change this value to <strong>./</strong>. The cache folder itself must have write permissions, or the script will not be able to store the cache files. The <strong>$cacheExpiration</strong> variable stores how long the cache will remain valid for before the  script needs to re-download more tweets. It is currently set to 1 hour  (3600 seconds), but feel free to adjust this to your particular needs,  depending on your number of visitors and how many times a day you tend  to tweet! The <strong>$maxTweets</strong> variable stores how many  tweets the script will display, and should normally be left alone  because Twitter only makes available the latest tweets in it’s API by  standard anyway. The final variable <strong>$twitterUrl</strong> is the beginning of the URL used to connect to Twitter, and should normally be OK as well.</p>
<p>Now that the initial class definition has been written, lets write the main method of the class, <strong>fetchTweets()</strong>. This will connect to Twitter, using the given username and password, if needed, and will pass the downloaded tweets to the <strong>writeCache()</strong> method to store them. Once the script has finished, it will return the  downloaded tweets as an array of associative arrays. Here is the code  for the <strong>fetchTweets()</strong> method:</p>
<pre class="brush:php">public function fetchTweets($username, $password = null) {
    if(empty($username)) 'Error: You have not provided your Twitter username.';
    if(is_file($this-&gt;cacheFolder . $username . '.xml') &amp;&amp;
        time() - filemtime($this-&gt;cacheFolder . $username . '.xml') &lt;= $this-&gt;cacheExpiration) {
        return $this-&gt;readCache($username);
    }
    if(!is_null($password)) {
        $stream = stream_context_create(array(
            'http'  =&gt;  array('header' =&gt; 'Authorization: Basic' . base64_encode($username . ':' . $password))
        ));
        $tweets = file_get_contents($this-&gt;twitterUrl . $username, false, $context);
    } else {
        $tweets = file_get_contents($this-&gt;twitterUrl . $username, false);
    }
    if($http_response_header[0] == 'HTTP/1.1 200 OK') {
        $cacheError = $this-&gt;writeCache($username, $tweets);
        if(empty($cacheError)) {
            return $this-&gt;readCache($username);
        } else {
            return $cacheError;
        }
    } elseif($http_response_header[0] == 'HTTP/1.1 401 Unauthorized') {
        return 'Error: Your Twitter password is invalid or missing for accessing a protected account.';
    } elseif($http_response_header[0] == 'HTTP/1.1 404 Not Found') {
        return 'Error: The Twitter username provided could not be found.';
    } else {
        return 'Error: Twitter is not available at this time.';
    }
}</pre>
<p>Now this method is quite long, since it’s doing an awful lot, so  we’ll go through it carefully. Firstly, the method takes two variables, <strong>$username</strong>, which is required, and <strong>$password</strong> which is optional. The <strong>$password</strong> variable only needs to be passed if the Twitter account you are  fetching tweets from is protected, otherwise do not bother passing this.  I will explain this more later. The <strong>$username</strong> is required, and the first line of the method returns a descriptive error if the username is not passed.</p>
<p>After checking the username, the method then checks the cache. The if  statement may look complex, but it is essentially doing two things,  checking if the cache file for this username is present in the cache  folder, and checking if the modification time of the file is within its  expiry limit. If these two conditions are met, the method reads straight  from the cache using the <strong>readCache()</strong> method and returns the cached tweets immediately. If either of these conditions fail, the method continues.</p>
<p>Next, the method connects to Twitter and downloads the tweets. This  is done in one of two ways. If the method was given a password in the <strong>$password</strong> variable, the connection to Twitter is made using a wrapper for a <a href="http://uk.php.net/stream_context_create" target="_blank">socket</a> which includes the HTTP headers required to authenticate with the  Twitter API, passing the username and password in a string as follows: <strong>username:password</strong>.  If no password was provided, the connection to Twitter is very simple.  In both cases, the Twitter URL is built using a concatenation of the  private <strong>$twitterUrl</strong> class variable, together with the username provided and the ‘.xml’ ending.</p>
<p>The connection to Twitter has been made, and any tweets have been  fetched, but before writing the data to the cache, the data must first  be verified. This is done using the <strong>$http_response_header</strong> array, which is automatically set when an HTTP connection is made in  PHP. The first line of these headers contains the basic HTTP response  code, and this is what will be checked using an if statement. One of  four outcomes can happen from this statement:</p>
<ul>
<li>The connection was successful, and the tweets were returned fine. The tweets are then sent to the <strong>writeCache()</strong> method to store them in the local cache. If the cache was successful, the tweets are returned using the <strong>readCache()</strong> method, otherwise an error message is displayed.</li>
<li>Twitter returned that the connection was not authorised. This means  that either the Twitter account is protected and no password was  provided, or that the password provided was incorrect.</li>
<li>Twitter returns that the username was not found.</li>
<li>If none of the other conditions are satisfied, it is assumed that  Twitter itself is down or offline, which seems to be a frequent  occurrence at times these days…</li>
</ul>
<p>This is the end of the first method! Now we have to write the methods  that were referred to in this method that read and write the cache.</p>
<p>Firstly, we will concentrate on the <strong>readCache()</strong> method, which is shown below:</p>
<pre class="brush:php">private function readCache($username) {
    $xml = simplexml_load_file($this-&gt;cacheFolder . $username . '.xml');
    if(is_object($xml)) {
        $tweets = array();
        foreach($xml-&gt;status as $status) {
            $tweets[] = array(
                'created'   =&gt;  (string) $status-&gt;created_at,
                'text'      =&gt;  (string) $status-&gt;text
            );
        }
        return array_slice($tweets, 0, $this-&gt;maxTweets);
    } else {
        return 'Error: Cache is corrupted or has been modified and is no longer valid.';
    }
}</pre>
<p>The method is given the username to read from, and attempts to load the file into an object using PHP’s <a href="http://uk.php.net/simplexml_load_file" target="_blank">SimpleXML</a> implementation. The returned value of the function must be an object,  otherwise the file is corrupted or does not exist, and so this is  established first using a simple check on the returned value. Next, an  array is initialised for the tweets to be stored in, and the method  iterates through each status stored in the cache. Each tweet will  contain the time the tweet was created, and the text of the tweet  itself. These are returned as XML objects, so they must be cast back  into string values. The <strong>array_slice()</strong> function uses the class variable <strong>$maxTweets</strong> to make sure that only that number of tweets can be returned. And  that’s it! Reading the cache is very simple, and now all we need to do  is write the cache when the tweets are downloaded.</p>
<p>The <strong>writeCache()</strong> method contains the following code:</p>
<pre class="brush:php">private function writeCache($username, $tweets) {
    if(is_dir($this-&gt;cacheFolder)) {
        if(is_writable($this-&gt;cacheFolder)) {
            if(!file_put_contents($this-&gt;cacheFolder . $username . '.xml', $tweets)) {
                return 'Error: The file could not be stored.';
            } else {
                return '';
            }
        } else {
            return 'Error: The cache folder is not writable.';
        }
    } else {
        return 'Error: The cache folder does not exist.';
    }
}</pre>
<p>Before the cache can be stored, a couple of conditions have to be  met. Firstly, the cache folder which is set as a class variable MUST be a  directory itself, and that directory MUST be writable, otherwise the  cache cannot be stored. If the writable error occurs, you may need to  set some permissions on the folder. Once these conditions have been met,  the method attempts to store the tweets in the cached folder. This  statement is cleverly contained inside an if condition, because the  function would return false if the storage failed. If no errors have  happened, the method returns an empty string, otherwise it returns  whatever error stopped the cache from storing.</p>
<p>This is it! Our Twitter class is now complete, and we can use it to  fetch some tweets from our account onto a webpage! This is the easy  step, and involves using an <a href="http://uk.php.net/manual/en/function.include.php" target="_blank"><strong>include()</strong></a> statement and creating an object of the Twitter class to use:</p>
<pre class="brush:php">include('QuickTwitter.class.php');
$twitter = new QuickTwitter();
$myTweets = $twitter-&gt;fetchTweets('zenithus');</pre>
<p>The above three lines of code will give you some tweets in the <strong>$myTweets</strong> variable, obviously remove my Twitter username and replace it with your  own, and pass the method a password too if your account is protected.  To quickly show the fetched tweets on your website, and display any  errors if needed, write some code similar to the following:</p>
<pre class="brush:php">if(is_array($myTweets)) {
    echo '
&lt;ul id="tweets"&gt;';
    foreach($myTweets as $tweet) {
        echo '
	&lt;li&gt;'
        . date('jS M Y (H:i)', strtotime($tweet['created']))
        . ' - ' . $tweet['text'] . '&lt;/li&gt;
';
    }
    echo '&lt;/ul&gt;
';
} else echo '

' . $myTweets . '

';</pre>
<p>This will display your tweets in a simple HTML unordered list, which  you can then style using CSS, but this can be changed to whatever you  need for your site. You can also change the format of the date displayed  using PHP’s <a href="http://uk.php.net/date" target="_blank"><strong>date()</strong></a> formatting characters.</p>
<p>If you have any comments or questions, please either email me or leave a comment on the post, thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://sitearticles.com/code/php-tutorial-fetch-and-display-tweets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

