<?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>Cumps.be &#187; Design Patterns</title>
	<atom:link href="http://www.cumps.be/tags/technology/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cumps.be</link>
	<description>Living my life...</description>
	<lastBuildDate>Thu, 10 Dec 2009 22:55:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Design Patterns &#8211; Proxy Pattern</title>
		<link>http://www.cumps.be/design-patterns-proxy-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-proxy-pattern/#comments</comments>
		<pubDate>Sat, 16 Aug 2008 19:09:20 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=81</guid>
		<description><![CDATA[Welcome back for another episode in the pattern series! This will also be the last article about Design Patterns, since I&#8217;ve finished reading the Head First Design Patterns book  
It&#8217;s been a very interesting journey, lots of new patterns learned, lots of knowledge gained, and now it&#8217;s time to apply them in real projects.
As [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Welcome back</strong> for another episode in the pattern series! This will also be the <strong>last article</strong> about Design Patterns, since I&#8217;ve finished reading the <a href="http://www.amazon.co.uk/gp/product/0596007124?ie=UTF8&#038;tag=destiny-21&#038;linkCode=as2&#038;camp=1634&#038;creative=6738&#038;creativeASIN=0596007124" title="Head First Design Patterns"><strong>Head First Design Patterns</strong></a> book <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It&#8217;s been a <strong>very interesting</strong> journey, lots of <strong>new patterns learned</strong>, lots of <strong>knowledge gained</strong>, and now it&#8217;s time to apply them in <strong>real projects</strong>.</p>
<p>As a summary, the <strong>overview</strong> of all articles about patterns, including the one we&#8217;re going to see today:</p>
<ul>
<li><a href="http://blog.cumps.be/long-absence-design-patterns/" title="Long Absence - Design Patterns"><strong>Long Absence &#8211; Design Patterns</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-strategy-pattern/" title="Design Patterns - Strategy Pattern"><strong>Design Patterns &#8211; Strategy Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-observer-pattern/" title="Design Patterns - Observer Pattern"><strong>Design Patterns &#8211; Observer Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-observer-event-pattern/" title="Design Patterns - Observer/Event Pattern"><strong>Design Patterns &#8211; Observer/Event Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-decorator-pattern/" title="Design Patterns - Decorator Pattern"><strong>Design Patterns &#8211; Decorator Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-factory-method-pattern/" title="Design Patterns - Factory Method Pattern"><strong>Design Patterns &#8211; Factory Method Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-abstract-factory-pattern/" title="Design Patterns - Abstract Factory Pattern"><strong>Design Patterns &#8211; Abstract Factory Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-singleton-pattern/" title="Design Patterns - Singleton Pattern"><strong>Design Patterns &#8211; Singleton Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-generic-singleton-pattern/" title="Design Patterns - Generic Singleton Pattern"><strong>Design Patterns &#8211; Generic Singleton Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-command-pattern/" title="Design Patterns - Command Pattern"><strong>Design Patterns &#8211; Command Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-adapter-pattern/" title="Design Patterns - Adapter Pattern"><strong>Design Patterns &#8211; Adapter Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-facade-pattern/" title="Design Patterns - Facade Pattern"><strong>Design Patterns &#8211; Facade Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-template-method-pattern/" title="Design Patterns - Template Method Pattern"><strong>Design Patterns &#8211; Template Method Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-iterator-pattern/" title="Design Patterns - Iterator Pattern"><strong>Design Patterns &#8211; Iterator Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-composite-pattern/" title="Design Patterns - Composite Pattern"><strong>Design Patterns &#8211; Composite Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-state-pattern/" title="Design Patterns - State Pattern"><strong>Design Patterns &#8211; State Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-proxy-pattern/" title="Design Patterns - Proxy Pattern"><strong>Design Patterns &#8211; Proxy Pattern</strong></a></li>
</ul>
<p><strong>Let&#8217;s get started!</strong> Make sure you&#8217;re seated comfortable, it&#8217;s going to be a <strong>long one</strong> today!</p>
<p>The definiton, as usual: &#8220;<strong>Provide a surrogate or placeholder for another object to control access to it.</strong>&#8220;</p>
<p>A new request popped up, we need to add in a <strong>multiplayer option</strong> in our game, featuring a <strong>Lobby</strong> where users can get in touch with each other.</p>
<p>This lobby is going to be running on <strong>another machine</strong>, or in our case, just another console application to illustrate it.</p>
<p>First of all, we&#8217;re going to start by adding an <strong>interface ILobby</strong> to define our lobby.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy1.gif" alt="ILobby Interface"></p>
<p>We&#8217;ll place this interface in a <strong>seperate library</strong>, to better illustrate the <strong>Proxy Pattern</strong> later on. This way you can <strong>clearly</strong> see on which machine a specific piece of code is located.</p>
<p>Time to create our actual Lobby <strong>implementation</strong>!</p>
<p>As mentioned before, we will create this in a seperate project to clearly show the code for the Lobby is <strong>not located on the same machine</strong> as our main client.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy2.gif" alt="Lobby Implementation"></p>
<p>A <strong>very simple</strong> Lobby implementation, containing nothing more than a <strong>List&lt;string&gt; of Users</strong>.</p>
<p>At this stage, we can have our Lobby on <strong>one machine</strong>, but how do we add users to it from <strong>another machine</strong>?</p>
<p>This is where the <strong>Proxy Pattern</strong> comes looking!</p>
<p>Just to make one thing clear, the Proxy pattern comes in <strong>many different shapes</strong>, we&#8217;re using it to give a client <strong>access</strong> to a remote object, by means of a <strong>placeholder</strong>, reminds you of the <strong>definition</strong>, doesn&#8217;t it?</p>
<p>In our case, it&#8217;s called a &#8216;<strong>remote proxy</strong>&#8216;, there is also a &#8216;<strong>virtual proxy</strong>&#8216;, a &#8216;<strong>protection proxy</strong>&#8216; and more.</p>
<p>A virtual proxy can for example serve as a placeholder for an object which is <strong>expensive</strong> to create, if you want to retrieve an image over the internet, you could display <strong>an icon</strong> via a proxy while the real image is loading <strong>in the background</strong>.</p>
<p>So, let&#8217;s create this <strong>placeholder</strong> on the <strong>client side</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy3.gif" alt="LobbyProxy Implementation"></p>
<p>By placing a <strong>reference</strong> to our previously created <strong>ILobby</strong>, this proxy allows our client to work with, what it <strong>believes</strong> to be, a <strong>real lobby object</strong>.</p>
<p>In reality however, their is <strong>no Lobby implementation in our client code at all</strong>, it is merely a placeholder which implements the correct interface.</p>
<p>You might have <strong>noticed</strong> the notion of a <strong>Socket</strong> already <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Our proxy object might implement the correct ILobby interface, if we want it working, we will <strong>eventually</strong> need to <strong>call</strong> our <strong>real Lobby object</strong>.</p>
<p>In a <strong>first step</strong> this is done using sockets to <strong>connect</strong> to the server and <strong>communicate</strong> with the <strong>real object</strong>.</p>
<p>Before you go screaming .NET Remoting, <strong>hold your horses!</strong> This is meant to <strong>illustrate</strong> what is going on <strong>behind the scenes</strong> with a remote proxy.</p>
<p>When you&#8217;re coming from the <strong>Java</strong> world, you might have heard people mentioning <strong>a Skeleton</strong>.</p>
<p>This is not something creepy, but simply a <strong>class on the server</strong> side which <strong>intercepts call</strong> from the Proxy, <strong>talks to the real object</strong> and <strong>sends</strong> the results back.</p>
<p>Here&#8217;s a <strong>small part</strong> of our <strong>Skeleton code</strong>:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy4.gif" alt="Proxy and Skeleton Code"></p>
<p>As you can see, the <strong>Proxy</strong> talks to the <strong>Skeleton</strong>, which talks to the <strong>Real Object</strong>, after which it sends the response back over the wire.</p>
<p>When we put all of this <strong>in action</strong>, we see the following happening:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy5.gif" alt="Testing Proxy Pattern"></p>
<p>Our main client <strong>talked to a remote Lobby</strong> and <strong>registered</strong> some users, <strong>great!</strong></p>
<p>Now that we&#8217;ve seen how a proxy serves as a <strong>placeholder</strong>, it&#8217;s time to <strong>clean this code</strong> and get rid of all the <strong>socket stuff</strong>.</p>
<p>Just a note, all the socket stuff in the project is <strong>highly unstable</strong> and <strong>not meant</strong> for production! <strong>Don&#8217;t use it!!</strong> It&#8217;s only meant for <strong>demo purposes</strong> <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Let&#8217;s work on the <strong>server side</strong> first by <strong>removing the Skeleton</strong> code, <strong>referencing System.Runtime.Remoting</strong>, and letting our Lobby class <strong>inherit MarshalByRefObject</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy6.gif" alt="Lobby Remoting Implementation"></p>
<p>Last step needed for our server is to <strong>expose</strong> the Lobby object through <strong>Remoting</strong>, which is nothing more than having something like our previous Skeleton code hidden <strong>behind the scenes</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy7.gif" alt="Exposing Lobby Remoting"></p>
<p>The only thing left to do now is to <strong>remove the Proxy</strong> class from our main project, and <strong>use Remoting</strong> to get an instance of <strong>ILobby</strong>, which acts as a proxy behind the scenes.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/proxy/proxy8.gif" alt="Utilizing Remoting Proxy"></p>
<p><strong>Resulting output</strong> when we run this version? <strong>Exactly the same!</strong> But a lot <strong>less work</strong> to implement <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>And that&#8217;s it, <strong>another pattern</strong> in our heads!</p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/proxy/proxy.zip" title="Proxy Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again to have a look at. When you run it, make sure your run the <strong>GameServer</strong> first, <strong>unblock</strong> it on your Windows Firewall, and then run the <strong>Proxy</strong> project.</p>
<p>Well, that&#8217;s it, the <strong>last part</strong> of my series. I hope you <strong>liked them</strong> and <strong>learned a lot</strong> from it. Be sure to keep on <strong>visiting</strong> for some other <strong>tech subjects</strong> coming up soon.</p>
<p>You can always subscribe to the <a href="http://blog.cumps.be/feed/" title="Rss Feed"><strong>RSS feed</strong></a> to stay informed.</p>
<p><strong>Thanks</strong> to the people who were <strong>generous</strong> enough to <strong>donate</strong> a little bit after reading some of these articles! (If you&#8217;d like to donate, simply <strong>use the PayPal button</strong> on the left <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p><strong>See you soon!</strong></p>
<p>Some additional information on the Proxy Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Proxy_pattern" title="Wikipedia - Proxy Pattern">Wikipedia &#8211; Proxy Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternProxy.aspx" title="Data &#038; Object Factory - Proxy Pattern">Data &#038; Object Factory &#8211; Proxy Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-proxy-pattern/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; State Pattern</title>
		<link>http://www.cumps.be/design-patterns-state-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-state-pattern/#comments</comments>
		<pubDate>Fri, 08 Aug 2008 08:09:31 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=79</guid>
		<description><![CDATA[It&#8217;s been a while again, but it&#8217;s time for another pattern. Today we&#8217;ll look at the State Pattern.
First of all, the definition: &#8220;Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.&#8220;
An additional request has surfaced today, we need to keep track if a unit [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been <strong>a while</strong> again, but it&#8217;s time for another pattern. Today we&#8217;ll look at the <strong>State Pattern</strong>.</p>
<p>First of all, the definition: &#8220;<strong>Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.</strong>&#8220;</p>
<p>An <strong>additional request</strong> has surfaced today, we need to keep track if a unit is <strong>alive or dead</strong> and let it respond differently based on the <strong>state</strong> it is in.</p>
<p>Initially we solved this by introducing a <strong>new enum</strong> called UnitState and adding lots of <strong>switch()</strong> statements to our code.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state1.gif" alt="Initial State Implementation"></p>
<p>In the <strong>long run</strong> however, this would mean we have to keep on going into those statements whenever a <strong>new state</strong> needs to get added, which isn&#8217;t exactly following the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/Closed Principle"><strong>Open/Closed Principle</strong></a> we talked about.</p>
<p>Let&#8217;s <strong>refactor</strong> this and introduce a new interface called <strong>IUnitState</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state2.gif" alt="State Interface"></p>
<p>Instead of using an enum, we&#8217;re going to introduce two <strong>new classes</strong>, which implement IUnitState to <strong>represent our different states</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state3.gif" alt="Concrete States"></p>
<p>By <strong>seperating the logic</strong> for different states in different classes, we can add a new state <strong>easily</strong>, by simply creating a new class, and we keep our code base structured.</p>
<p>For example, the most <strong>simple state</strong> looks like this:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state4.gif" alt="State Implementation"></p>
<p>When we pull all of this together we get the following <strong>class diagram</strong>, illustrating two concrete states and the state interface.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state5.gif" alt="State Pattern Class Diagram"></p>
<p>To the outside, whenever the <strong>internal state</strong> changes, it looks like the object, GameUnit, changed it&#8217;s type because a different concrete state is providing an <strong>implementation</strong> for the actions.</p>
<p>When we <strong>test</strong> this code, we can see the behaviour of internal state <strong>changing</strong> after the first Kill() command.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/state/state6.gif" alt="Testing State Pattern"></p>
<p>I realize this isn&#8217;t the best example given to illustrate the State Pattern, I&#8217;m not quite that happy with it, <strong>stretching</strong> the game example like that, sometimes it works out, sometimes it feels a <strong>little forced</strong>, like today. I hope it made sense, be sure to check out the sites below for some <strong>other examples</strong> as well.</p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/state/state.zip" title="State Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again so you can have a look.</p>
<p>Some additional information on the State Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/State_pattern" title="Wikipedia - State Pattern">Wikipedia &#8211; State Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternState.aspx" title="Data &#038; Object Factory - State Pattern">Data &#038; Object Factory &#8211; State Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-state-pattern/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Composite Pattern</title>
		<link>http://www.cumps.be/design-patterns-composite-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-composite-pattern/#comments</comments>
		<pubDate>Sun, 27 Jul 2008 11:22:00 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=76</guid>
		<description><![CDATA[It&#8217;s been a little while again. I blame myself for installing World Of Warcraft again, too addictive.
Anyway, time for the Composite Pattern. This is one I&#8217;m having a little trouble with to describe clearly.
Let&#8217;s start with the definition: &#8220;Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a little <strong>while</strong> again. I blame myself for installing <strong>World Of Warcraft</strong> again, too addictive.</p>
<p>Anyway, time for the <strong>Composite Pattern</strong>. This is one I&#8217;m having a <strong>little trouble</strong> with to describe clearly.</p>
<p>Let&#8217;s start with the definition: &#8220;<strong>Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.</strong>&#8220;</p>
<p>The easiest way to understand this pattern is the notion of the <strong>tree structure</strong> in the definition, if you can make a tree in code, you can apply this pattern <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>An <strong>additional requirement</strong> has popped up for our game yesterday. We used to only have TacticalMoves, but now it&#8217;s needed to have those defined in a more <strong>granular</strong> way, where one move might exist out of <strong>several submoves</strong>.</p>
<p>First of all, we define a new class, called <strong>TacticalComponent</strong>, which will serve as a <strong>base class</strong> for our TacticalMove and the <strong>new type</strong> we&#8217;ll introduce.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite1.gif" alt="Composite Pattern Component"></p>
<p>As you can see, this class consists mainly out of <strong>two parts</strong>, the properties to hold some game-specific information and additional methods to deal with the new feature request of having submoves, which are nothing more then <strong>children</strong>.</p>
<p>This TacticalComponent is an <strong>abstract class</strong>, where each method and property <strong>throws an exception</strong>, and only defines them as <strong>virtual instead of abstract</strong>.</p>
<p>By doing this, we give the subclasses the choice which methods and properties they are going to <strong>override</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite2.gif" alt="Composite Pattern Class Diagram"></p>
<p>In our case both classes implement <strong>Description</strong> and <strong>Name</strong>, but only TacticalPlan implements the <strong>parent-child logic</strong>.</p>
<p>The nice part of all of this is, you have <strong>already encountered</strong> this pattern, for example when working in <strong>Windows Forms</strong>, where components are Controls and the Print method is used to render a control.</p>
<p>No matter which control you ask to render, it will render itself <strong>and</strong> all its children, without you having to walk the tree.</p>
<p>Likewise in our TacticalPlan, the <strong>Print method</strong> displays itself along with <strong>all its children</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite3.gif" alt="Print"></p>
<p>Having introduced these two new classes, we can now rewrite our WorldOrders class to only accept <strong>one TacticalComponent</strong>, and treat it as a whole.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite4.gif" alt="Rewritten WorldOrders class"></p>
<p>The <strong>test code</strong> to illustrate this now composes the tree as follows:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite5.gif" alt="Test Code"></p>
<p>Resulting in the <strong>following orders</strong>:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/composite/composite6.gif" alt="Testing Composite Pattern"></p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/composite/composite.zip" title="Composite Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again. This was one of the more difficult patterns to explain so far, so <strong>don&#8217;t be too hard</strong> on me <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Some additional information on the Composite Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Composite_pattern" title="Wikipedia - Composite Pattern">Wikipedia &#8211; Composite Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternComposite.aspx" title="Data &#038; Object Factory - Composite Pattern">Data &#038; Object Factory &#8211; Composite Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-composite-pattern/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Iterator Pattern</title>
		<link>http://www.cumps.be/design-patterns-iterator-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-iterator-pattern/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 12:36:54 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=69</guid>
		<description><![CDATA[Time for the next part in our series, the Iterator Pattern.
Let&#8217;s start with the definition: &#8220;Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.&#8220;
Recently, we have received a request to add the notion of orders to our game. To this end, we created a new class, called [...]]]></description>
			<content:encoded><![CDATA[<p>Time for the next part in <a href="http://blog.cumps.be/tags/design-patterns/" title="Design Patterns"><strong>our series</strong></a>, the <strong>Iterator Pattern</strong>.</p>
<p>Let&#8217;s start with the definition: &#8220;<strong>Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.</strong>&#8220;</p>
<p>Recently, we have received a request to add the notion of <strong>orders</strong> to our game. To this end, we created a new class, called <strong>TacticalMove</strong> which represents an order.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator1.gif" alt="TacticalMove Class"></p>
<p>We have asked two of our <strong>junior developers</strong> to create a class for each faction which contains <strong>all orders</strong> for a given faction.</p>
<p>After a while, they came up with the following <strong>implementations</strong>:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator2.gif" alt="EVA and LEGION Classes"></p>
<p>As you can see, our developers both took a <strong>different approach</strong> to the problem.</p>
<p>One developer used a <strong>List</strong> to store the orders, while the other stored them in a <strong>fixed-size array</strong>.</p>
<p>If we want to create a <strong>WorldOrders</strong> class, which is able to display <strong>all orders</strong> of both factions, it would look a bit like this:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator3.gif" alt="Initial WorldOrders Class"></p>
<p>As you notice from the <strong>red colors</strong>, this initial approach has quite a few <strong>flaws</strong>.</p>
<p>First of all, we are programming against <strong>concrete implementations</strong> again, Eva and Legion.</p>
<p>We are also showing the <strong>internals of our classes</strong> to the outside world, since we have both collection representations showing.</p>
<p>And lastly, because we are pushing our internal storage through, we have <strong>two different kind of loops</strong> to display them. <i>(Forget the foreach operator exists for a moment)</i></p>
<p>Let&#8217;s <strong>fix</strong> this last part by introducing a new interface, called <strong>Iterator</strong> which has a <strong>HasNext()</strong> and <strong>Next()</strong> method, designed to <strong>iterate over a collection</strong>.</p>
<p>When we have this interface, we need to create two <strong>new iterators</strong> for each implementation, one holding a List <strong>internally</strong>, while the other is storing the array.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator4.gif" alt="Iterator Implementations"></p>
<p>The only thing we need to change to our Eva and Legion class now is to <strong>remove the GetOrders()</strong> method and <strong>replace it</strong> by the <strong>GetIterator()</strong> method.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator5.gif" alt="GetIterator Methods"></p>
<p>Having done this change, allows us to go back to the <strong>WorldOrders</strong> and replace the two different loops by <strong>one identical loop</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator6.gif" alt="Iterator Usage"></p>
<p>We still need to <strong>pull out the concrete</strong> Eva and Legion classes however. Let&#8217;s do this by introducing a new interface, called <strong>IFactionAI</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator7.gif" alt="IFactionAI"></p>
<p>When we <strong>implement</strong> this new interface to our Eva and Legion classes, we have <strong>decoupled</strong> the WorldOrders class from them.</p>
<p>Taking a look at the class diagram, with the <a href="http://wiki.cumps.be/_media/files/blog/iterator/iterator.gif" title="Iterator Pattern Official Diagram"><strong>official names</strong></a>, we can now see WorldOrders is only working with <strong>Iterators and interfaces</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator8.gif" alt="Iterator Pattern Class Diagram"></p>
<p>And that&#8217;s the <strong>Iterator Pattern</strong> in action!</p>
<p>But wait, just like the <a href="http://blog.cumps.be/design-patterns-observer-event-pattern/" title="Design Patterns - Observer/Event Pattern"><strong>Observer Pattern</strong></a>, we can create it ourselves, or we can use some of the features from the <strong>.NET Framework</strong>!</p>
<p>Just like we used events earlier on, we can use <strong>IEnumerator and IEnumerable</strong> this time.</p>
<p><strong>Refactoring</strong> our code to use these, results in the following classes remaining:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator9.gif" alt="IEnumerable and IEnumerator"></p>
<p>As you can see, there is <strong>no more LegionIterator</strong> either, since List <strong>provides</strong> a GetEnumerator method itself, which we simply call.</p>
<p>Time to <strong>test</strong> all this code we just wrote and <strong>try it out</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/iterator/iterator10.gif" alt="Testing IEnumerable and IEnumerator"></p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/iterator/iterator.zip" title="Iterator Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again. Since this was quite a long article, <strong>have a look</strong> at the code, I&#8217;ve placed the code for each step in <strong>seperate folders</strong> so you can <strong>compare the changes</strong> between steps.</p>
<p>Some additional information on the Iterator Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Iterator_pattern" title="Wikipedia - Iterator Pattern">Wikipedia &#8211; Iterator Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternIterator.aspx" title="Data &#038; Object Factory - Iterator Pattern">Data &#038; Object Factory &#8211; Iterator Pattern Overview</a>.</li>
</ul>
<p>Also have a look at this personal post: <a href="http://blog.cumps.be/wanted-friends/" title="Wanted: Friends!"><strong>Wanted: Friends!</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-iterator-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Template Method Pattern</title>
		<link>http://www.cumps.be/design-patterns-template-method-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-template-method-pattern/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 08:22:32 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=65</guid>
		<description><![CDATA[Time for yet another pattern, the Template Method Pattern. Have a look at all the other patterns in the series as well.
The definition: &#8220;Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm&#8217;s structure.&#8220;
Let&#8217;s add an additional [...]]]></description>
			<content:encoded><![CDATA[<p>Time for yet another pattern, the <strong>Template Method Pattern</strong>. Have a look at all the other patterns in <a href="http://blog.cumps.be/tags/design-patterns/" title="Design Patterns"><strong>the series</strong></a> as well.</p>
<p>The definition: &#8220;<strong>Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm&#8217;s structure.</strong>&#8220;</p>
<p>Let&#8217;s add an <strong>additional requirement</strong> to our game. We need different types of <strong>renderers</strong> for our GUI, the main screen is in 3D, while the map is displayed in 2D.</p>
<p>Both layouts follow a <strong>specific drawing order</strong>. First the background, then the units, on screen instructions, special effects and a border. If this order is wrong, it would be possible for the background to <strong>overlap</strong> the units, which we <strong>don&#8217;t want</strong>.</p>
<p>We&#8217;ll start by creating a new <strong>base class</strong> for our renderers, with some abstract methods which make up <strong>the algorithm</strong> of drawing the screen.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/template/template1.gif" alt="Base Class"></p>
<p>As you can see, there are two non-abstract methods. DrawBorder() which is <strong>common functionality</strong> for every render and RenderScreen() which is actually a <strong>Template Method</strong>.</p>
<p>The Template Method <strong>defines</strong> the steps used in the algorithm, <strong>without actually implementing</strong> the steps itself.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/template/template2.gif" alt="Template Method"></p>
<p>As you can see from the comments, with the perfect implementation, <strong>RenderScreen()</strong> should be a method which <strong>can&#8217;t be overridden</strong> by child classes. C# doesn&#8217;t support this however.</p>
<p>When we create our <strong>two renderers</strong> and have the discipline to not hide RenderScreen(), the class diagram for the <strong>Template Method Pattern</strong> looks like this:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/template/template3.gif" alt="Class Diagram Template Method Pattern"></p>
<p>If we <strong>test</strong> this code, we notice that the <strong>order of rendering</strong> a screen is the same, but that each engine <strong>implements the steps differently</strong>, or not at all.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/template/template4.gif" alt="Testing Template Method Pattern"></p>
<p>And that&#8217;s the <strong>Template Method Pattern</strong>! I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/template/template.zip" title="Template Method Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again to have a look at.</p>
<p>Also, since I only aggregate <strong>technological posts</strong>, I&#8217;d like to mention this personal post to have a look at: <a href="http://blog.cumps.be/wanted-friends/" title="Wanted: Friends!"><strong>Wanted: Friends!</strong></a></p>
<p>Some additional information on the Template Method Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Template_method_pattern" title="Wikipedia - Template Method Pattern">Wikipedia &#8211; Template Method Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternTemplate.aspx" title="Data &#038; Object Factory - Template Method Pattern">Data &#038; Object Factory &#8211; Template Method Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-template-method-pattern/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Facade Pattern</title>
		<link>http://www.cumps.be/design-patterns-facade-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-facade-pattern/#comments</comments>
		<pubDate>Sun, 20 Jul 2008 15:11:17 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=61</guid>
		<description><![CDATA[Time for another, simple, design pattern. The Facade Pattern.
I&#8217;m going to need a break soon, getting a bit burned out, which never is a good thing.
Anyway, the definition of today&#8217;s pattern: &#8220;Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.&#8220;
The [...]]]></description>
			<content:encoded><![CDATA[<p>Time for another, <strong>simple</strong>, design pattern. The <strong>Facade Pattern</strong>.</p>
<p>I&#8217;m going to <strong>need a break</strong> soon, getting a bit burned out, which never is a good thing.</p>
<p>Anyway, the definition of today&#8217;s pattern: &#8220;<strong>Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.</strong>&#8220;</p>
<p>The <strong>hardest part</strong> of writing articles for this series isn&#8217;t so much understanding the patterns itself, but <strong>coming up with examples</strong> with somewhat <strong>make sense</strong> in my gaming example. So, please <strong>forgive me</strong> if they sometimes are a bit <strong>far fetched</strong>, like today <img src='http://www.cumps.be/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Let&#8217;s say we have some <strong>complex subsystem</strong> which handles everything about <strong>storage</strong>. Some classes for our CD drive, some for our hard disk, memory and much more.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/facade/facade1.gif" alt="Complex Subsystem"></p>
<p>If we need to <strong>load a new map</strong>, one way to do it would be to load up the cd, copy it to the hd, load it into memory and stop the cd from spinning.</p>
<p>Or, we could also <strong>create a new class</strong>, which defines some more <strong>high-level operations</strong> such as LoadMap(), which takes care of dealing with the subsystem.</p>
<p>This way, our clients can use a <strong>simple interface</strong>, but if they really need to, can still go straight to the subsystem classes themselves, as opposed to the <a href="http://blog.cumps.be/design-patterns-adapter-pattern/" title="Design Patterns - Adapter Pattern"><strong>Adapter Pattern</strong></a>, where you only talked to the Adapter.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/facade/facade3.gif" alt="Facade Class"></p>
<p>And <strong>that&#8217;s it really</strong>, Facade and Adapter are very alike, and both <strong>very simple</strong>.</p>
<p>Let&#8217;s have a look at the <strong>full diagram</strong>, and image the subsystem contains a lot more classes than I drew <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><img src="http://wiki.cumps.be/_media/files/blog/facade/facade2.gif" alt="Facade Pattern Class Diagram"></p>
<p>Time to <strong>test it</strong> and have our client use the <strong>StorageFacade</strong> directly, instead of the subsystem.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/facade/facade4.gif" alt="Testing Facade Pattern"></p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/facade/facade.zip" title="Facade Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again, worth a look.</p>
<p>In my opinion, the Facade Pattern is a helper pattern to make your code <strong>easier to use</strong> and more user-friendly, other developers being the user.</p>
<p>Some additional information on the Facade Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Facade_pattern" title="Wikipedia - Facade Pattern">Wikipedia &#8211; Facade Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternFacade.aspx" title="Data &#038; Object Factory - Facade Pattern">Data &#038; Object Factory &#8211; Facade Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-facade-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Adapter Pattern</title>
		<link>http://www.cumps.be/design-patterns-adapter-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-adapter-pattern/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 22:23:45 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/?p=56</guid>
		<description><![CDATA[We&#8217;ve seen quite a few patterns so far, and I&#8217;m glad so many people like them.
They turned out to be the most popular posts I&#8217;ve ever written when it comes to development. Thanks!  
A little overview for the late joiners:

Long Absence &#8211; Design Patterns
Design Patterns &#8211; Strategy Pattern
Design Patterns &#8211; Observer Pattern
Design Patterns &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve seen <strong>quite a few</strong> patterns so far, and I&#8217;m glad so many people like them.</p>
<p>They turned out to be the <strong>most popular</strong> posts I&#8217;ve ever written when it comes to development. <strong>Thanks!</strong> <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>A little <strong>overview</strong> for the late joiners:</p>
<ul>
<li><a href="http://blog.cumps.be/long-absence-design-patterns/" title="Long Absence - Design Patterns"><strong>Long Absence &#8211; Design Patterns</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-strategy-pattern/" title="Design Patterns - Strategy Pattern"><strong>Design Patterns &#8211; Strategy Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-observer-pattern/" title="Design Patterns - Observer Pattern"><strong>Design Patterns &#8211; Observer Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-observer-event-pattern/" title="Design Patterns - Observer/Event Pattern"><strong>Design Patterns &#8211; Observer/Event Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-decorator-pattern/" title="Design Patterns - Decorator Pattern"><strong>Design Patterns &#8211; Decorator Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-factory-method-pattern/" title="Design Patterns - Factory Method Pattern"><strong>Design Patterns &#8211; Factory Method Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-abstract-factory-pattern/" title="Design Patterns - Abstract Factory Pattern"><strong>Design Patterns &#8211; Abstract Factory Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-singleton-pattern/" title="Design Patterns - Singleton Pattern"><strong>Design Patterns &#8211; Singleton Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-generic-singleton-pattern/" title="Design Patterns - Generic Singleton Pattern"><strong>Design Patterns &#8211; Generic Singleton Pattern</strong></a></li>
<li><a href="http://blog.cumps.be/design-patterns-command-pattern/" title="Design Patterns - Command Pattern"><strong>Design Patterns &#8211; Command Pattern</strong></a></li>
</ul>
<p>Today we&#8217;ll have a look at the <strong>Adapter Pattern</strong>.</p>
<p>As usual, the definition: &#8220;<strong>Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn&#8217;t otherwise because of incompatible interfaces.</strong>&#8220;</p>
<p>To continue on our little game, we received a <strong>third party library</strong> from another team, containing some <strong>buildings to include</strong> in our game.</p>
<p>The developers of this library didn&#8217;t work with <strong>IBuildings</strong> however, but call it a <strong>Structure</strong>, making all of our code which interacts with IBuilding <strong>unusable</strong>.</p>
<p>If we look at the definition, we can see the <strong>Adapter Pattern</strong> is the perfect solution for this, since we need to <strong>convert the interface</strong> of the third party Structure into the IBuilding we expect, so that they can <strong>work together</strong> as if their interface was compatible.</p>
<p>Let&#8217;s have a look on how <strong>their interface</strong> looks like first.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/adapter/adapter1.gif" alt="Third Party Library - Adaptee"></p>
<p>There are some differences in the logic used in their implementation. We both have a <strong>Description</strong>, but the way we manage Power consumption is <strong>totally different</strong>.</p>
<p>Time to <strong>adapt</strong> their interface to the one we <strong>expect</strong>.</p>
<p>We&#8217;ll do this by creating a new class, a so called <strong>adapter</strong>, which <strong>implements</strong> the IBuilding interface, since we expect that one, and which uses <strong>composition</strong> to encapsulate a Structure.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/adapter/adapter2.gif" alt="Adapter Class"></p>
<p>As you can see, our Adapter is actually <strong>behaving as an IBuilding</strong> to the rest of our code, <strong>adapting the calls</strong> to our interface into the third party their interface.</p>
<p>And <strong>that&#8217;s it</strong> really! The easiest way I remember this pattern is by thinking of <strong>electrical adapters</strong>, <strong>changing</strong> the socket from US to UK, or <strong>transforming</strong> the voltages.</p>
<p>Time to have a look at the <strong>full diagram</strong>, with the <a href="http://wiki.cumps.be/_media/files/blog/adapter/adapter.gif" title="Adapter Pattern - ULM Diagram"><strong>official names</strong></a> written against it again:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/adapter/adapter3.gif" alt="Adapter Pattern Class Diagram"></p>
<p>Let&#8217;s also write some <strong>test code</strong> to see the Adapter Pattern in action.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/adapter/adapter4.gif" alt="Testing Adapter Pattern"></p>
<p>We can <strong>re-use</strong> all of our existing code with the new Structures, since it&#8217;s <strong>behaving like an IBuilding</strong> right now.</p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/adapter/adapter.zip" title="Adapter Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again to have a look at.</p>
<p>Feel free to leave any <strong>feedback</strong>.</p>
<p>Some additional information on the Adapter Pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Wrapper_pattern" title="Wikipedia - Adapter Pattern">Wikipedia &#8211; Adapter Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternAdapter.aspx" title="Data &#038; Object Factory - Adapter Pattern">Data &#038; Object Factory &#8211; Adapter Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-adapter-pattern/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Command Pattern</title>
		<link>http://www.cumps.be/design-patterns-command-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-command-pattern/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 22:02:14 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-command-pattern/</guid>
		<description><![CDATA[What&#8217;s a lonely geek to do late in the evening? Write about the Command Pattern of course&#8230;
Let&#8217;s start with the definition: &#8220;Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations.&#8220;
And now, time for the spec I just made up: Our UI has [...]]]></description>
			<content:encoded><![CDATA[<p>What&#8217;s a lonely <strong>geek</strong> to do late in the evening? Write about the <strong>Command Pattern</strong> of course&#8230;</p>
<p>Let&#8217;s start with the definition: &#8220;<strong>Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations.</strong>&#8220;</p>
<p>And now, time for the spec I just made up: Our UI has <strong>three buttons</strong> at the bottom of the screen, which contain <strong>various actions</strong>. These actions are different depending on the <strong>selected item</strong> however. We need to implement this piece of UI code, <strong>without it having any knowledge of our game units</strong>.</p>
<p>How would we approach this? Let&#8217;s say these buttons are nothing more than <strong>placeholders</strong>, to be <strong>filled</strong> with real buttons whenever a unit is selected. Our game engine will respond to a selected event and <strong>create and pass on</strong> the real buttons to our UI code.</p>
<p>So, our UI code will only need to know about <strong>one thing</strong>, a button. Let&#8217;s create an <strong>interface</strong> for this type of button, and coincidentally name it <strong>ICommand</strong> <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><img src="http://wiki.cumps.be/_media/files/blog/command/command3.gif" alt="Command Interface"></p>
<p>We&#8217;ll code our UI code against the <strong>ICommand</strong>, respecting to program <strong>against an interface and not an implementation</strong>.</p>
<p>At the end, we&#8217;ll need some <strong>real implementations</strong> as well however. So let&#8217;s create some &#8220;buttons&#8221;, which I&#8217;ll call <strong>Commands</strong> from now on.</p>
<p>Right now we only have two types of items, <strong>GameUnits and IBuildings</strong>. Each Command will perform an action against one of these, encapsulating the object through <strong>composition</strong>.</p>
<p>For this example, we can make a <strong>GameUnit</strong> turn <strong>Aggressive, Normal and Suicidal</strong>. We can also power <strong>buildings on and off</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/command/command4.gif" alt="Command Objects"></p>
<p>Notice these Commands themselves are written against <strong>interfaces</strong> as well, our <strong>good habits</strong> are already starting to pay off.</p>
<p>The <strong>NoCommand</strong> is a little tricky, it&#8217;s just a <strong>dummy object</strong>, which sometimes is called a <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" title="Wikipedia - Null Object Pattern"><strong>Null Object</strong></a> as well. It&#8217;s being used for buttons which <strong>don&#8217;t do anything</strong>, basically their <strong>default value</strong>.</p>
<p>It&#8217;s time to create our UI code, the <strong>GameControls</strong> class. This class will contain the <strong>three buttons</strong>, ICommands, and helper methods to <strong>assign</strong> real buttons into the placeholder slots, as well as triggering button <strong>clicks</strong>.</p>
<p>Additionally, there&#8217;s <strong>another requirement</strong> which has surfaced. We want to be able to <strong>undo</strong> our last action, whenever possible, can&#8217;t undo suicide <img src='http://www.cumps.be/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>We&#8217;ll accomplish this by <strong>storing the last ICommand</strong>, and when an undo action is needed, call the <strong>Undo() method</strong> on it, since each command provides the <strong>exact opposite</strong> of Execute() in it&#8217;s Undo() method.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/command/command5.gif" alt="Invoker Object"></p>
<p>That&#8217;s all the code that was needed to implement the <strong>Command Pattern</strong> actually.</p>
<p>Our GameControls class has <strong>no idea</strong> GameUnit or IBuilding exists, it&#8217;s <strong>totally decoupled</strong> from them.</p>
<p>By using Command objects, we can treat them as <strong>little blocks</strong> which can be stored in a queue for <strong>multiple level undo</strong>, we can let several threads pop commands of a <strong>queue</strong> to process them in parallel, and <strong>much more</strong>.</p>
<p>Let&#8217;s have a look at the <strong>full diagram</strong>, with the <a href="http://en.wikipedia.org/wiki/Image:Command_Design_Pattern_Class_Diagram.png" title="Wikipedia - Command Pattern - Class Diagram"><strong>official names</strong></a> written on them as well.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/command/command1.gif" alt="Command Pattern"></p>
<p>Time to put our code into action and <strong>test it</strong>.</p>
<p>Let&#8217;s imagine we have a full blown engine, and when a unit is selected, various events get fired, resulting in the <strong>creation</strong> of the correct <strong>ICommand objects</strong>, being passed to our GameControls UI code, which causes buttons to be <strong>displayed</strong> on screen. We&#8217;ll also simulate a <strong>click</strong> on the various <strong>buttons</strong> and the <strong>undo button</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/command/command2.gif" alt="Testing Command Pattern"></p>
<p>That&#8217;s it! I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/command/command.zip" title="Command Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> for the Command Pattern so you can <strong>have a look</strong> at the code of the Command Objects and the details of the GameControls.</p>
<p><strong>Questions? Feedback? Comment!!</strong></p>
<p>Some additional information on the Command pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Command_pattern" title="Wikipedia - Command Pattern">Wikipedia &#8211; Command Pattern</a>.</li>
<li><a href="http://www.dofactory.com/patterns/patterncommand.aspx" title="Data &#038; Object Factory - Command Pattern">Data &#038; Object Factory &#8211; Command Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-command-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Generic Singleton Pattern</title>
		<link>http://www.cumps.be/design-patterns-generic-singleton-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-generic-singleton-pattern/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 11:58:51 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-generic-singleton-pattern/</guid>
		<description><![CDATA[A little follow up from yesterday&#8217;s Singleton Pattern, where I asked for some help on how you would approach a generic singleton.
With the help of Andrew Stevenson and ExNihilo, we came up with the following Generic Singleton Pattern:

Using Reflection, the private constructor is called to create an instance of the class.
Whenever a Singleton is needed [...]]]></description>
			<content:encoded><![CDATA[<p>A little follow up from yesterday&#8217;s <a href="http://blog.cumps.be/design-patterns-singleton-pattern/" title="Design Patterns - Singleton Pattern"><strong>Singleton Pattern</strong></a>, where I asked for some help on how you would approach a <strong>generic singleton</strong>.</p>
<p>With the help of <a href="http://weblogs.asp.net/andrewseven/" title="Andrew Stevenson"><strong>Andrew Stevenson</strong></a> and <strong>ExNihilo</strong>, we came up with the following <strong>Generic Singleton Pattern</strong>:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/singleton/genericsingleton.gif" alt="Generic Singleton Pattern" /></p>
<p>Using <strong>Reflection</strong>, the <strong>private</strong> constructor is called to create an instance of the class.</p>
<p>Whenever a Singleton is needed now, the only thing to do is to inherit Singleton and pass in the class itself as T, along with making the constructor private.</p>
<p>I&#8217;ve updated <a href="http://wiki.cumps.be/_media/files/blog/singleton/singleton2.zip" title="Generic Singleton Pattern - VS 2008 Solution"><strong>yesterday&#8217;s solution</strong></a> to contain this new code as well, have a look.</p>
<p>I&#8217;d like this post to draw some attention from <strong>CLR guru&#8217;s</strong> to have a look at the implementation and point out <strong>possible problems</strong> and how to solve them.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-generic-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Singleton Pattern</title>
		<link>http://www.cumps.be/design-patterns-singleton-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-singleton-pattern/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 15:54:13 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-singleton-pattern/</guid>
		<description><![CDATA[Today we&#8217;ll have a look at a well known pattern, the Singleton Pattern. Most people have already heard about this one.
The definition: &#8220;Ensure a class has only one instance and provide a global point of access to it.&#8220;
Why would you want to only have one instance of a class?
Well, you could have one Configuration class [...]]]></description>
			<content:encoded><![CDATA[<p>Today we&#8217;ll have a look at a well known pattern, the <strong>Singleton Pattern</strong>. Most people have already heard about this one.</p>
<p>The definition: &#8220;<strong>Ensure a class has only one instance and provide a global point of access to it.</strong>&#8220;</p>
<p>Why would you want to only have <strong>one instance</strong> of a class?</p>
<p>Well, you could have one <strong>Configuration</strong> class for example, which reads some configuration settings at runtime, after which they remain available to your application.</p>
<p>It makes <strong>sense</strong> to only have one instance of this class, since having multiple could cause you to suddenly end up with <strong>different configuration settings</strong>.</p>
<p>Now, there are <strong>different</strong> Singleton Pattern <strong>implementations</strong> out there, which makes it <strong>interesting</strong> to have a look at it anyway.</p>
<p>First of all, let&#8217;s look at the <strong>basics</strong> of how a Singleton works. Since we&#8217;re working with our game example, a good singleton would be a reference to our <strong>hardware</strong>, the GraphicsCard, we should have <strong>only one instance</strong> of it, who knows what would happen if we start mixing up various instances <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>To make sure there is only one instance of a certain class, we let that <strong>class itself</strong> manage it&#8217;s instantiation, instead of creating it ourselves using the <strong>new() operator</strong>.</p>
<p><strong>Preventing</strong> others from calling new() on our class is done by making the <strong>constructor private</strong>. This way <strong>nobody</strong> can instantiate the class directly.</p>
<p>But how do we get an instance back then?</p>
<p>We provide a <strong>static method</strong> in the class itself, <strong>returning an instance</strong> of itself. By doing this, we can create one instance upon the <strong>first request</strong> and keep returning the <strong>same instance</strong> upon further requests.</p>
<p>This is also a form of <strong>lazy loading</strong>, since it only gets created when it is requested for the first time.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/singleton/singleton1.gif" alt="Basic Singleton"></p>
<p>Where&#8217;s the catch you might ask? <strong>Multi-threading</strong>! This simple implementation of a Singleton is <strong>not thread-safe</strong>!</p>
<p>It is possible for <strong>multiple threads</strong> to both execute the null check together, both evaluate it to true, since there is <strong>no instance yet</strong>, and then both threads create an instance, ending up with <strong>multiple instances</strong> instead of one.</p>
<p>Luckily, there&#8217;s a <strong>solution</strong>. I&#8217;ll cut straight to the point and give the <strong>thread-safe, lazy loading version</strong>. There are other thread-safe implementations out there, which you can read more about at <a href="http://www.yoda.arachsys.com/csharp/singleton.html" title="Implementing the Singleton Pattern in C#"><strong>Implementing the Singleton Pattern in C#</strong></a>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/singleton/singleton2.gif" alt="Thread-Safe Singleton"></p>
<p>As you can see, the <strong>actual instance</strong> is held inside a private sealed <strong>nested class</strong>, which is inside the GraphicsCard class. When the Instance property is called for the <strong>first time</strong>, it will instantiate a GraphicsCard in a <strong>thread-safe</strong> way, thanks to the Nested class, and upon subsequent requests, the <strong>same instance</strong> will be returned.</p>
<p>It&#8217;s <strong>elegant</strong>, and doesn&#8217;t use any special <strong>language keywords</strong> like lock() in C# or synchronize in Java.</p>
<p>I think it&#8217;s quite <strong>easy</strong> to set up a Singleton like this, once you&#8217;ve done it once, you can do it <strong>everywhere</strong>.</p>
<p>With C# and <strong>generics</strong> however, we can be even more <strong>lazy</strong>, which is why I tried out throwing the Singleton Pattern into the following code.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/singleton/singleton3.gif" alt="Generic Thread-Safe Singleton"></p>
<p>Now the only thing we need to do when we want to <strong>create a singleton</strong> is create a class, inheriting from Singleton passing the <strong>class itself</strong> in as the <strong>generic T</strong>.</p>
<p>The usage of both classes is <strong>identical</strong> afterwards, as you can see from this small snippet:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/singleton/singleton4.gif" alt="Singleton Usage"></p>
<p><strong>That&#8217;s it</strong>, one of the easiest to understand patterns conceptually, but with some <strong>common pitfalls</strong> when implementing it.</p>
<p>There is <strong>one big issue</strong> bothering me with the <strong>generics</strong> approach however, hopefully someone can <strong>help me</strong> out on this, in an elegant way.</p>
<p>As it is coded right now, you can do <strong>new GraphicsCardGeneric()</strong>, which is something I <strong>don&#8217;t want</strong>, since you run the risk of ending up with <strong>multiple instances</strong> again.</p>
<p>I <strong>can&#8217;t add</strong> a private constructor however, since the <strong>generics break</strong> down then, requiring a <strong>public parameterless constructor</strong> to do <strong>new T()</strong> inside the Nested class.</p>
<p>If anyone has a nice solution to get around this, while keeping generics, <strong>please comment</strong> and let me know. Personally I feel safer using the <strong>non-generics solution</strong> for now, since it locks down new() instantiation of the Singleton.</p>
<p>As usual, <a href="http://wiki.cumps.be/_media/files/blog/singleton/singleton.zip" title="Singleton Pattern - VS 2008 Solution"><strong>the project</strong></a> is available again to look at for further detail.</p>
<p>Some additional information on the Singleton pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Singleton_pattern" title="Wikipedia - Singleton Pattern">Wikipedia &#8211; Singleton Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternSingleton.aspx" title="Data &#038; Object Factory - Singleton Pattern">Data &#038; Object Factory &#8211; Singleton Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Abstract Factory Pattern</title>
		<link>http://www.cumps.be/design-patterns-abstract-factory-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-abstract-factory-pattern/#comments</comments>
		<pubDate>Sun, 13 Jul 2008 18:14:26 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-abstract-factory-pattern/</guid>
		<description><![CDATA[Time to continue from yesterday&#8217;s Factory Method Pattern by exploring the Abstract Factory Pattern.
Right now, we have created separate classes for both factions&#8217; units (CyborgCommando and Ghostalker). Let&#8217;s change this so each faction has identical base classes containing logic, but slightly different configuration depending on the faction they belong to.
We&#8217;ll do this by implementing the [...]]]></description>
			<content:encoded><![CDATA[<p>Time to continue from yesterday&#8217;s <a href="http://blog.cumps.be/design-patterns-factory-method-pattern/" title="Design Patterns - Factory Method Pattern"><strong>Factory Method Pattern</strong></a> by exploring the <strong>Abstract Factory Pattern</strong>.</p>
<p>Right now, we have created separate classes for both factions&#8217; units (<strong>CyborgCommando and Ghostalker</strong>). Let&#8217;s change this so each faction has <strong>identical base classes</strong> containing logic, but slightly <strong>different configuration</strong> depending on the faction they belong to.</p>
<p>We&#8217;ll do this by implementing the <strong>Abstract Factory Pattern</strong>. I always mix this one up with the Factory Method Pattern, but it finally <strong>got through</strong> to me while writing the code for this post.</p>
<p>With Factory Method, we have an abstract base class containing logic and calling our abstract factory methods, which return a real implementation <strong>via subclasses</strong>.</p>
<p>While the Abstract Factory is passed into an object where it is used as <strong>composition</strong>, and the real factory is supplied at runtime, decoupling the usage of our factory from the real implementation.</p>
<p>Anyway, time for the definition and then some code to make everything clear. &#8220;<strong>Provide an interface for creating families of related or dependent objects without specifying their concrete classes.</strong>&#8220;</p>
<p>First of all, let&#8217;s get rid of our faction specific units and <strong>replace them</strong> by generic ones.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory1.gif" alt="Generic Game Units"></p>
<p>You&#8217;ll notice the <strong>GameUnit</strong> has been given a new constructor, an <strong>abstract class</strong> containing only <strong>abstract methods</strong>.</p>
<p>This class forms the definition of the Abstract Factory Pattern, it&#8217;s an <strong>interface</strong> to create related objects <strong>without specifying</strong> a concrete class.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory2.gif" alt="Abstract Factory Class"></p>
<p>Our GameUnit class is <strong>not</strong> working with a concrete type, but with <strong>an interface</strong>, decoupling it from a real faction implementation.</p>
<p>We aren&#8217;t much with just this interface, so let&#8217;s <strong>create an implementation</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory3.gif" alt="Factory Implementation"></p>
<p>As you can see, the classes we used to illustrate the <a href="http://blog.cumps.be/design-patterns-strategy-pattern/" title="Design Patterns - Strategy Pattern"><strong>Strategy Pattern</strong></a> have been moved to this factory implementation, which means our GameUnit and all other unit implementations are now working with <strong>interfaces</strong> rather than concrete implementations.</p>
<p>Another thing left to do, is to let the units <strong>get their information</strong> from the abstract factory.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory4.gif" alt="Interrogating the Abstract Factory"></p>
<p>All that is left, is a small change to our two InfantryFactories to <strong>pass in</strong> the correct <strong>FactionDetailsFactory</strong> to each unit, and our test case is ready to run again, without having to change it.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory5.gif" alt="Providing a Factory Implementation"></p>
<p>You might wonder what the <strong>IBuilding</strong> interface is suddenly doing there, well, I <strong>cleaned</strong> the code a bit up and decided to place everything in separate files <strong>as it should</strong>. Never done it before to keep it simple for these articles, but I didn&#8217;t like the code adding up.</p>
<p>With the <strong>Abstract Factory Pattern</strong> implemented, our results looks like this:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory6.gif" alt="Abstract Factory Pattern"></p>
<p>So, here&#8217;s <a href="http://wiki.cumps.be/_media/files/blog/abstractfactory/factory2.zip" title="Abstract Factory Pattern - VS 2008 Solution"><strong>the uploaded solution</strong></a> again, changed <strong>quite a bit</strong> since last time, <strong>take your time</strong> to have a look at it.</p>
<p>As usual, <strong>feedback</strong> is much <strong>appreciated</strong>.</p>
<p>Some additional information on the Abstract Factory pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" title="Wikipedia - Abstract Factory Pattern">Wikipedia &#8211; Abstract Factory Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternAbstract.aspx" title="Data &#038; Object Factory - Abstract Factory Pattern">Data &#038; Object Factory &#8211; Abstract Factory Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-abstract-factory-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Factory Method Pattern</title>
		<link>http://www.cumps.be/design-patterns-factory-method-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-factory-method-pattern/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 19:28:26 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-factory-method-pattern/</guid>
		<description><![CDATA[I present you with the next pattern in our series, the Factory Method! It took a while to get it out due to a stay in the hospital. (All is fine now :p)
The chapter I&#8217;m currently reading deals with both factory patterns, Factory Method and Abstract Factory, in one chapter, but I&#8217;m going to write [...]]]></description>
			<content:encoded><![CDATA[<p>I present you with the <strong>next pattern</strong> in <a href="http://blog.cumps.be/tags/design-patterns/" title="Design Patterns">our series</a>, the <strong>Factory Method</strong>! It took a while to get it out due to a stay in the hospital. (All is fine now :p)</p>
<p>The chapter I&#8217;m currently reading deals with both factory patterns, <strong>Factory Method</strong> and <strong>Abstract Factory</strong>, in one chapter, but I&#8217;m going to write an <strong>article on each</strong> to limit the length.</p>
<p>First of all, the definition: &#8220;<strong>Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.</strong>&#8220;</p>
<p>Today we were given specs to <strong>add a building</strong> to our game. This building will <strong>create infantry</strong> units, set their <strong>behaviour</strong> to a specific setting and send them to a given <strong>waypoint</strong> after creation.</p>
<p>We start with a simplistic approach of creating an <strong>InfantryFactory class</strong>, which represents a building and contains a <strong>building-specific</strong> waypoint and unit behaviour setting to be given to new units.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory1.gif" alt="Simple Unit Factory Building"></p>
<p>It does the job, a specific unit is created based on a <strong>runtime parameter</strong>, it is given its behaviour and sent to a specific destination.</p>
<p>However, when we need to <strong>add new units</strong>, we need to open up this class every time again and <strong>change</strong> inside of it, which violates the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/Closed Principle"><strong>Open/Closed Principle</strong></a> we talked about <a href="http://blog.cumps.be/design-patterns-decorator-pattern/" title="Design Patterns - Decorator Pattern">last time</a>.</p>
<p>Let&#8217;s <strong>isolate</strong> what changes and move it to its own method, just to illustrate we <strong>understand</strong> the part that is most subject to change.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory2.gif" alt="Isolating Change"></p>
<p>Since the <strong>CreateUnit</strong> method is still inside the same class, we still have <strong>a problem</strong>. The BuildUnit method is a <strong>fine piece of code</strong> now however, it works with <strong>GameUnit objects</strong> instead of actual implementations.</p>
<p>Once this code passes our quality assurance it can be <strong>extended</strong> as much as wanted without having to <strong>modify</strong> it. Let&#8217;s get this entire class to meet our quality standards now by <strong>implementing</strong> the Factory Method.</p>
<p>Our InfantryFactory class forms a <strong>nice base</strong> for creating units and performing various logic, let&#8217;s <strong>lock it down</strong> for modification by making it abstract and <strong>throwing the CreateUnit implementation out</strong> as well.</p>
<p>To throw its implementation out, we are going to define CreateUnit as <strong>an abstract method</strong>, forcing subclasses to implement it. Let&#8217;s create <strong>two factories</strong> for both our factions.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory3.gif" alt="Factory Method Pattern"></p>
<p>As you can see, I&#8217;ve taken the liberty to add some <strong>more units</strong> since last time, to illustrate how our two <strong>factories decide</strong> which class to <strong>instantiate</strong> in the CreateUnit method. Which is exactly what the <strong>Factory Method</strong> definition describes.</p>
<p>We defined an interface for creating an object, the <strong>abstract CreateUnit</strong> method, and let the subclasses, <strong>Barracks and HandOfNod</strong>, decide which class to instantiate. We made our InfantryFactory <strong>open for extension and closed for modification</strong>!</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory4.gif" alt="Factory Method Pattern - Code"></p>
<p>When we test this code, you can see our objects are always using <strong>abstract classes or interfaces</strong> (an abstract class is also called an interface sometimes, in the sense of the English language, not in the C# keyword).</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory5.gif" alt="Factory Method Test Case"></p>
<p>The <strong>result</strong> after all this coding is this little output, and the fact that we learned another pattern, the <strong>Factory Method</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/factorymethod/factory6.gif" alt="Factory Method Test Case Output"></p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/factorymethod/factory1.zip" title="Factory Method Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again. If you have any questions or feedback, please <strong>comment</strong>.</p>
<p>Some additional information on the Factory Method pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Factory_method_pattern" title="Wikipedia - Factory Method Pattern">Wikipedia &#8211; Factory Method Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternFactory.aspx" title="Data &#038; Object Factory - Factory Method Pattern">Data &#038; Object Factory &#8211; Factory Method Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-factory-method-pattern/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Decorator Pattern</title>
		<link>http://www.cumps.be/design-patterns-decorator-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-decorator-pattern/#comments</comments>
		<pubDate>Sun, 29 Jun 2008 19:35:06 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-decorator-pattern/</guid>
		<description><![CDATA[Following up on the Observer/Event Pattern, it&#8217;s time for the third pattern, the Decorator Pattern.
The definition: &#8220;Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.&#8220;
Continuing on our little game, let&#8217;s say we are able to create buildings and have just an IBuilding interface and one building.

Each building [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on the <a href="http://blog.cumps.be/design-patterns-observer-event-pattern/" title="Design Patterns - Observer/Event Pattern"><strong>Observer/Event Pattern</strong></a>, it&#8217;s time for the third pattern, the <strong>Decorator Pattern</strong>.</p>
<p>The definition: &#8220;<strong>Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</strong>&#8220;</p>
<p>Continuing on our <strong>little game</strong>, let&#8217;s say we are able to create buildings and have just an <strong>IBuilding interface</strong> and one building.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/decorator/decorator1.gif" alt="Simple Building"></p>
<p>Each building has a description and a given <strong>power usage</strong> cost, which is simply hardcoded in the class right now.</p>
<p>After a while, our boss hired an <strong>external company</strong> to take over development with regards to the buildings and tasked them with making <strong>buildings upgradeable</strong>.</p>
<p>The first approach they took was too simply add <strong>new building classes</strong> to the game, for <strong>each possible</strong> upgrade.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/decorator/decorator2.gif" alt="Class Explosion"></p>
<p>This however leads to an <strong>infinite amount</strong> of possibilities and a <strong>nightmare to maintain</strong>.</p>
<p>If we look at the definition of the <strong>Decorator Pattern</strong>, it seems to offer a good <strong>alternative</strong> to all this inheriting to add in new functionality.</p>
<p>Also, adding additional responsibilities <strong>dynamically</strong> means we <strong>don&#8217;t have to change</strong> the code of the IBuilding and NormalBuilding either. By doing this we are honoring the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/Closed Principle"><strong>Open/Closed Principle</strong></a>, which says &#8220;software entities (classes, modules, functions, etc.) should be <strong>open for extension</strong>, but <strong>closed for modification</strong>&#8220;.</p>
<p>How are we going to add these additional things dynamically? We&#8217;ll <strong>decorate</strong> our initial NormalBuilding with upgrades, giving us flexibility to equip a building with <strong>any upgrade combination</strong> we like.</p>
<p>When we mention decorating, think about <strong>wrapping</strong>. We are going to wrap an <strong>instance</strong> of IBuilding in a decorator, acting as a <strong>shell</strong> around the class, <strong>passing calls</strong> to our decorator along to the wrapped instance, <strong>modifying the results</strong> when needed.</p>
<p>It&#8217;s also possible to <strong>chain decorators</strong> together, making it possible to decorate a NormalBuilding with two Turrets, a SAM installation and a Laser. This is done because a decorated object is still of the type IBuilding, and can be decorated <strong>again and again</strong>.</p>
<p>Eventually we&#8217;ll end up with the following <strong>class diagram</strong>. Note, the WrappedBuilding has a protected getter and a private setter.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/decorator/decorator3.gif" alt="Decorator Pattern"></p>
<p>Now we have a set of buildings, which implement IBuilding and <strong>one decorator base class</strong>, BuildingUpgradeDecorator, from which <strong>all possible</strong> decorations inherit. This decorator class has to <strong>implement IBuilding</strong> as well, so it can be re-decorated.</p>
<p>With the above classes, it&#8217;s possible to <strong>compose buildings</strong> as we desire, as shown below.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/decorator/decorator4.gif" alt="Decorator Usage"></p>
<p>When we run this code, the call to the Power property is being <strong>passed through</strong> all decorators to the lowest level, our NormalBuilding, and returned all the way back, <strong>getting incremented</strong> with the additional power usage for each decorator/upgrade in the mean time.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/decorator/decorator5.gif" alt="Decorator Output"></p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/decorator/decorator.zip" title="Decorator Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> again so you can have a look on how the decorator base class and individual decorators are programmed.</p>
<p>Some additional information on the Decorator pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Decorator_pattern" title="Wikipedia - Decorator Pattern">Wikipedia &#8211; Decorator Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternDecorator.aspx" title="Data &#038; Object Factory - Decorator Pattern">Data &#038; Object Factory &#8211; Decorator Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-decorator-pattern/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Observer/Event Pattern</title>
		<link>http://www.cumps.be/design-patterns-observer-event-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-observer-event-pattern/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 15:13:07 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-observerevent-pattern/</guid>
		<description><![CDATA[Yesterday I described the Observer Pattern and mentioned that the .NET CLR provides this functionality through events and delegates.
Let&#8217;s have a look on how to implement this right now.
First of all, we can get rid of our ISubject and IObserver interfaces. And we&#8217;ll replace it by a push notification mechanism.
Push, because we&#8217;ll pass the required [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I described the <a href="http://blog.cumps.be/design-patterns-observer-pattern/" title="Observer Pattern"><strong>Observer Pattern</strong></a> and mentioned that the .NET CLR provides this functionality through <strong>events and delegates</strong>.</p>
<p>Let&#8217;s have a look on how to <strong>implement</strong> this right now.</p>
<p>First of all, we can <strong>get rid</strong> of our ISubject and IObserver interfaces. And we&#8217;ll replace it by a <strong>push notification</strong> mechanism.</p>
<p>Push, because we&#8217;ll pass the required information along <strong>to the observers</strong> when notifying them, as <strong>opposed to pull</strong>, where the observers had to extract it themselves from the subject.</p>
<p>Since we&#8217;ll be pushing out the information, we need a <strong>custom class</strong> defining which information is interesting. We&#8217;ll create this by <strong>inheriting</strong> from the <a href="http://msdn.microsoft.com/en-us/library/system.eventargs.aspx" title="MSDN - EventArgs"><strong>EventArgs class</strong></a>, by doing this it will be <strong>very easy</strong> to set up an event in the next step.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/event/event1.gif" alt="Custom EventArgs Class"></p>
<p>As you can see, this is a very small class, with a <strong>descriptive name</strong>, containing the new location of our unit.</p>
<p>You can&#8217;t see it on this diagram, but the NewLocation property only has a <strong>public getter</strong>, and a <strong>private setter</strong>, since our observers will only have to <strong>extract data</strong> from this class.</p>
<p>So, we got our small <strong>information holding</strong> class, now it&#8217;s time to change our GameUnit class to <strong>get rid</strong> of all the logic of <strong>maintaining a list</strong> of observers and subscription logic.</p>
<p>We&#8217;ll <strong>replace</strong> the ISubject logic by an event of the type <strong>EventHandler&lt;PositionChangedEventArgs&gt;</strong>. By doing this, we <strong>expose an event</strong> (<strong>PositionChanged</strong>) to our observers upon which they can <strong>subscribe themselves</strong> whenever they want as well as <strong>unsubscribe</strong> when needed.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/event/event2.gif" alt="Observer/Event Pattern"></p>
<p>Note that this event is <strong>strongly typed</strong>, containing a strongly typed information set, making it <strong>easy</strong> for our observers to get the information they need.</p>
<p>Using this method, we can have a set of EventArgs classes as small data holders, after which subjects can <strong>expose events</strong> using those custom EventArgs to the outside world, making <strong>sending out notifications</strong> very easy.</p>
<p>Observers on their side can <strong>easily subscribe</strong> to any of the events exposed by using a single line of code, and perform their logic (<strong>_PositionChanged methods</strong>) whenever they get a notification.</p>
<p>Have a look at the <a href="http://wiki.cumps.be/_media/files/blog/event/event.zip" title="Observer/Event Pattern - VS 2008 Solution"><strong>uploaded solution</strong></a>  to see the exact syntax of this method. We&#8217;re using <strong>delegates</strong> with <strong>generics</strong>, the <strong>+= operator</strong> and <strong>throwing and handling</strong> events.</p>
<p>Again, if you have any <strong>questions</strong>, feel free to leave them behind.</p>
<p>Some additional information on the Observer/Event pattern:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms954621.aspx" title="Exploring the Observer Design Pattern">MSDN &#8211; Exploring the Observer Design Pattern</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-observer-event-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Observer Pattern</title>
		<link>http://www.cumps.be/design-patterns-observer-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-observer-pattern/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 19:21:08 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-observer-pattern/</guid>
		<description><![CDATA[Yesterday we saw the Strategy Pattern. Today I want to talk about the Observer Pattern.
I got a bit of a mixed feeling about this pattern, since in the .NET world, we got events and delegates making this pattern somewhat unneeded.
However, it&#8217;s good to know how it works, since it&#8217;s used behind the scenes in the [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday we saw the <a href="http://blog.cumps.be/design-patterns-strategy-pattern/" title="Strategy Pattern"><strong>Strategy Pattern</strong></a>. Today I want to talk about the <strong>Observer Pattern</strong>.</p>
<p>I got a bit of a mixed feeling about this pattern, since in the .NET world, we got <strong>events and delegates</strong> making this pattern somewhat unneeded.</p>
<p>However, it&#8217;s good to know how it works, since it&#8217;s used <strong>behind the scenes</strong> in the .NET CLR when working with events. Besides, better know too much than too little, <strong>knowledge is power</strong>.</p>
<p>Also, I&#8217;m planning to write a <strong>separate post</strong> after this to go into the C# specific implementation anyway.</p>
<p>First, the definition again: &#8220;<strong>Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</strong>&#8220;</p>
<p>Let&#8217;s continue with our example from yesterday, were we made an object model to describe some <strong>game characters</strong>. The next requirement came in, and we need to <strong>display movement</strong> of our units on the screen.</p>
<p>Initially, we are given <strong>one screen</strong>, a big overview of a battle map, where all units are displayed on and move around on.</p>
<p>An easy <strong>quick approach</strong> would be to simply add some coordinates information to our GameUnit class and add in a Move() method which gets called whenever the unit moves.</p>
<p>This Move() method would then simply call our BattleMapDisplay class to <strong>inform</strong> it of its new location.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/observer/observer1.gif" alt="Quick Hacky Notification"></p>
<p>That would work, <strong>for now&#8230;</strong> But what if we want to <strong>add in</strong> a different type of display?</p>
<p>Let&#8217;s say we want to add in a OverviewDisplay as our main view. Then we have to go and <strong>change our GameUnit</strong> class to inform this screen as well. <strong>Bad</strong>. Let&#8217;s fix this up a little.</p>
<p>If we look at it from a <strong>higher level</strong> again, all our displays are doing is <strong>observing</strong> our game units and <strong>acting upon any change</strong> in them. So, one display is actually an <strong>Observer</strong> of our GameUnit, the <strong>Subject</strong>. And there we have it, our displays have a one-to-many relation with a GameUnit and want to be <strong>notified</strong> when it <strong>changes</strong> it state, the <strong>Observer Pattern</strong>&#8217;s exact definition. <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Remember from last time? <strong>Program to an interface, not an implementation.</strong></p>
<p>When we set up a system to let objects communicate state changes to each other, the only thing these objects should know about each other is a <strong>common communication interface</strong>. Let&#8217;s create that one by adding two additional interfaces, <strong>IObserver and ISubject</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/observer/observer2.gif" alt="Notification Interfaces"></p>
<p>Now that we have our new interfaces, we can change the GameUnit class to hold a <strong>collection of IObserver</strong> objects. Together with providing two methods for additional observers to <strong>subscribe themselves</strong> so they can get notifications when the GameUnit changes.</p>
<p>By implementing it this way, we can <strong>easily add</strong> new displays or other objects to our application, which can <strong>easily stay informed</strong> about our units as long as they <strong>implement</strong> the IObserver interface and subscribe themselves with the units.</p>
<p>The GameUnit <strong>doesn&#8217;t care</strong> about which kind of object is on the receiving end of the notification, and so <strong>won&#8217;t have to be changed</strong> whenever an new Observer is added. The Observer however will have to make checks in its Update() method to determine which ISubject is being returned.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/observer/observer3.gif" alt="Observer Pattern"></p>
<p>Whenever a GameUnit moves right now, it informs all screens about this, <strong>passing itself</strong> along so the observers can get information out of the object.</p>
<p>And <strong>that&#8217;s it really</strong>, the Observer Pattern isn&#8217;t all that hard, it&#8217;s a <strong>simple notification mechanism</strong>. In a next post I&#8217;ll talk more about delegates and events to have a look on how the Observer Pattern is <strong>implemented in the CLR</strong>.</p>
<p>If you have any <strong>questions</strong> about this pattern, please leave them in the <strong>comments</strong>, something you want to know, something I overlooked or was unclear about, just ask, it&#8217;s from having a <strong>dialog</strong> we learn the most.</p>
<p>As usual, I <a href="http://wiki.cumps.be/_media/files/blog/observer/observer.zip" title="Observer Pattern - VS 2008 Solution"><strong>uploaded the solution</strong></a> I used for this post so you have a detailed look at the code used.</p>
<p>Some additional information on the Observer pattern:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Observer_pattern" title="Wikipedia - Observer Pattern">Wikipedia &#8211; Observer Pattern</a>.</li>
<li><a href="http://www.dofactory.com/Patterns/PatternObserver.aspx" title="Data &#038; Object Factory - Observer Pattern">Data &#038; Object Factory &#8211; Observer Pattern Overview</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-observer-pattern/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Strategy Pattern</title>
		<link>http://www.cumps.be/design-patterns-strategy-pattern/</link>
		<comments>http://www.cumps.be/design-patterns-strategy-pattern/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 11:44:43 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/design-patterns-strategy-pattern/</guid>
		<description><![CDATA[The first pattern I want to talk about is the Strategy pattern, which always reminds me about the Command &#038; Conquer games so I&#8217;ll simply use it as an example  
First of all, the definition: &#8220;Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from [...]]]></description>
			<content:encoded><![CDATA[<p>The first pattern I want to talk about is the <strong>Strategy pattern</strong>, which always reminds me about the <a href="http://en.wikipedia.org/wiki/Command_&#038;_Conquer" title="Wikipedia - Command &#038; Conquer">Command &#038; Conquer</a> games so I&#8217;ll simply use it as an example <img src='http://www.cumps.be/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>First of all, the definition: &#8220;<strong>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</strong>&#8220;</p>
<p>I&#8217;m bad at remembering definitions or trying to imagine what they really mean, so let&#8217;s just go ahead and try to <strong>create something</strong> and <strong>learn as we go</strong>, eventually we&#8217;ll end up implementing the Strategy pattern and you&#8217;ll &#8216;<strong>get it</strong>&#8216; for the rest of your life, without a definition.</p>
<p>A long time ago, we made a <strong>simple strategy game</strong>, having only 2 units, a soldier and a tank, both were able to shoot at each other which we implemented as follows:</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/strategy/strategy1.gif" alt="Simple Class Model"></p>
<p>The Shoot() logic is contained in the base <strong>GameUnit</strong> class, since it&#8217;s identical for both units. Each unit takes care of drawing itself.</p>
<p>After a while, we receive a request to add in an Engineer, which is a unit used to take over buildings and more importantly, <strong>he can&#8217;t shoot</strong>.</p>
<p>If we just added an Engineer class similar to the Soldier one, he would be able to shoot as well, which <strong>we don&#8217;t want</strong>. We could for this once just <strong>override</strong> the Shoot() method for the Engineer and <strong>make it empty</strong>.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/strategy/strategy2.gif" alt="Hiding methods - Maintenance Hell"></p>
<p>Can you already see where this is going to end up? <strong>Maintenance Nightmare!</strong></p>
<p>Eventually we end up with lots of useless code being <strong>repeated</strong> for every class which has a different shooting logic, where you have to open up every class to figure out all the available implementations. <strong>Let&#8217;s not implement it like this!</strong></p>
<p>What if we were to get rid of the Shoot() logic in the GameUnit class and make an <strong>IShootable interface</strong> for the units that can actually shoot?</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/strategy/strategy3.gif" alt="Interface - Code Duplication"></p>
<p>That looks a bit cleaner, but wait! We simply <strong>shifted the nightmare</strong>, because now the Soldier and Tank have <strong>identically</strong> the same code in their Shoot() method. This isn&#8217;t the solution either, let&#8217;s take a look at what our <strong>higher level goal</strong> actually is.</p>
<p>We can see the part that <strong>changes</strong> is how a unit shoots. If we take a closer look at shooting and implementing future classes, it is very possible we&#8217;ll end up with a class that has a very <strong>different shooting algorithm</strong> or has upgradeable parts, changing the way it shoots. You could say the way a unit shoots is a <strong>behaviour</strong> of a unit.</p>
<p>Remember the definition of the Strategy pattern? The shooting behaviour we have just defined is actually an <strong>algorithm</strong>, while the requirement of units being able to get upgraded implies the behaviours have to be changed at run time, making them <strong>interchangeable</strong>.</p>
<p>Making things interchangeable usually means having less things hard-coded in your application, which reminds of a great saying: <a href="http://en.wikipedia.org/wiki/Design_Patterns" title="Wikipedia - Gang Of Four - Design Patterns">Program to an &#8216;interface&#8217;, not an &#8216;implementation&#8217;</a>.</p>
<p>Let&#8217;s <strong>separate</strong> all our shooting logic from our units and create a totally new set of classes defining all possible shooting behaviours.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/strategy/strategy4.gif" alt="Behaviour Set - Family of Algorithms"></p>
<p>Now it&#8217;s only a matter of letting our GameUnit use these behaviours. We&#8217;ll do this by programming against the <strong>IShootingBehaviour interface</strong> instead of against an implementation. This way we can <strong>dynamically replace</strong> the behaviour at run time, and have a very flexible programming model towards the future.</p>
<p>Adding a new way of shooting is simply a matter of <strong>adding a new class</strong> implementing the IShootingBehaviour interface after which all our units could use it.</p>
<p><img src="http://wiki.cumps.be/_media/files/blog/strategy/strategy5.gif" alt="Strategy Pattern"></p>
<p><strong>And that&#8217;s it!</strong> We&#8217;ve implemented the <strong>Strategy pattern</strong>. We defined a <strong>family of algorithms</strong> (IShootingBehaviour), we <strong>encapsulated</strong> each one (NormalShot, CantShoot, ThrowKnifes) and made them <strong>interchangeable</strong> (ShootingBehaviour property).</p>
<p>Each client can define his algorithm as we currently did in the constructor, by setting the property to the desired implementation. In a future pattern we&#8217;ll see how to set this different, since it&#8217;s not that pretty doing it in the constructor.</p>
<p>Note that even though we are setting a shooting implementation via the constructor, it is possible to change the way a unit shoots <strong>at runtime</strong> by setting the <strong>ShootingBehaviour property</strong>.</p>
<p>I&#8217;ve <a href="http://wiki.cumps.be/_media/files/blog/strategy/strategy.zip" title="Strategy Pattern - VS 2008 Solution"><strong>uploaded the sample project</strong></a> I have used while learning this pattern so you can have a look at the code representing the above diagrams yourself.</p>
<p>Some additional information on the Strategy pattern:</p>
<ul>
<li><a href="http://www.dofactory.com/Patterns/PatternStrategy.aspx" title="Data &#038; Object Factory - Strategy Pattern">Data &#038; Object Factory &#8211; Strategy Pattern Overview</a>.</li>
<li><a href="http://en.wikipedia.org/wiki/Strategy_pattern" title="Wikipedia - Strategy Pattern">Wikipedia &#8211; Strategy Pattern</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/design-patterns-strategy-pattern/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Long Absence &#8211; Design Patterns</title>
		<link>http://www.cumps.be/long-absence-design-patterns/</link>
		<comments>http://www.cumps.be/long-absence-design-patterns/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 17:25:27 +0000</pubDate>
		<dc:creator>David Cumps</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Technologie]]></category>

		<guid isPermaLink="false">http://blog.cumps.be/long-absence-design-patterns/</guid>
		<description><![CDATA[It&#8217;s been a while again, real life issues managed to take over all time&#8230; But, I&#8217;m regaining ground and winning back some of it  
For the first time in years, I&#8217;ve managed to get around reading a real book again. Last week I picked up a copy of Head First Design Patterns and started [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while again, real life issues managed to take over all time&#8230; But, I&#8217;m regaining ground and winning back some of it <img src='http://www.cumps.be/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>For the first time in years, I&#8217;ve managed to get around reading a real book again. Last week I picked up a copy of <a href="http://www.amazon.co.uk/gp/product/0596007124?ie=UTF8&amp;tag=destiny-21&amp;linkCode=as2&amp;camp=1634&amp;creative=6738&amp;creativeASIN=0596007124" title="Head First Design Patterns">Head First Design Patterns</a> and started on it yesterday. As far as I can tell, only read the first chapter so far, <strong>it&#8217;s a great book!</strong></p>
<p>It&#8217;s not like a usual learning book, which tend to be pretty dull when it comes to formatting or the type of language used. This book reads like a <strong>great story</strong>, filled with <strong>images</strong> to clarify and explain concepts. The images aren&#8217;t even optional, when you really want to learn, you have to read them to get the full picture.</p>
<p>As a form of learning, I plan to write a blog post about <strong>each pattern</strong> I finish, explaining it in my own words, so it &#8217;sticks&#8217; a lot better for myself as well, <strong>helping others</strong> at the same time. Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cumps.be/long-absence-design-patterns/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
