It'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'm having a little trouble with to describe clearly.

Let's start with the definition: "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."

The easiest way to understand this pattern is the notion of the tree structure in the definition, if you can make a tree in code, you can apply this pattern :)

An additional requirement has popped up for our game yesterday. We used to only have TacticalMoves, but now it's needed to have those defined in a more granular way, where one move might exist out of several submoves.

First of all, we define a new class, called TacticalComponent, which will serve as a base class for our TacticalMove and the new type we'll introduce.

Composite Pattern Component

As you can see, this class consists mainly out of two parts, 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 children.

This TacticalComponent is an abstract class, where each method and property throws an exception, and only defines them as virtual instead of abstract.

By doing this, we give the subclasses the choice which methods and properties they are going to override.

Composite Pattern Class Diagram

In our case both classes implement Description and Name, but only TacticalPlan implements the parent-child logic.

The nice part of all of this is, you have already encountered this pattern, for example when working in Windows Forms, where components are Controls and the Print method is used to render a control.

No matter which control you ask to render, it will render itself and all its children, without you having to walk the tree.

Likewise in our TacticalPlan, the Print method displays itself along with all its children.

Print

Having introduced these two new classes, we can now rewrite our WorldOrders class to only accept one TacticalComponent, and treat it as a whole.

Rewritten WorldOrders class

The test code to illustrate this now composes the tree as follows:

Test Code

Resulting in the following orders:

Testing Composite Pattern

I've uploaded the solution again. This was one of the more difficult patterns to explain so far, so don't be too hard on me :)

Some additional information on the Composite Pattern:

 

Time for the next part in our series, the Iterator Pattern.

Let's start with the definition: "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation."

Recently, we have received a request to add the notion of orders to our game. To this end, we created a new class, called TacticalMove which represents an order.

TacticalMove Class

We have asked two of our junior developers to create a class for each faction which contains all orders for a given faction.

After a while, they came up with the following implementations:

EVA and LEGION Classes

As you can see, our developers both took a different approach to the problem.

One developer used a List to store the orders, while the other stored them in a fixed-size array.

If we want to create a WorldOrders class, which is able to display all orders of both factions, it would look a bit like this:

Initial WorldOrders Class

As you notice from the red colors, this initial approach has quite a few flaws.

First of all, we are programming against concrete implementations again, Eva and Legion.

We are also showing the internals of our classes to the outside world, since we have both collection representations showing.

And lastly, because we are pushing our internal storage through, we have two different kind of loops to display them. (Forget the foreach operator exists for a moment)

Let's fix this last part by introducing a new interface, called Iterator which has a HasNext() and Next() method, designed to iterate over a collection.

When we have this interface, we need to create two new iterators for each implementation, one holding a List internally, while the other is storing the array.

Iterator Implementations

The only thing we need to change to our Eva and Legion class now is to remove the GetOrders() method and replace it by the GetIterator() method.

GetIterator Methods

Having done this change, allows us to go back to the WorldOrders and replace the two different loops by one identical loop.

Iterator Usage

We still need to pull out the concrete Eva and Legion classes however. Let's do this by introducing a new interface, called IFactionAI.

IFactionAI

When we implement this new interface to our Eva and Legion classes, we have decoupled the WorldOrders class from them.

Taking a look at the class diagram, with the official names, we can now see WorldOrders is only working with Iterators and interfaces.

Iterator Pattern Class Diagram

And that's the Iterator Pattern in action!

But wait, just like the Observer Pattern, we can create it ourselves, or we can use some of the features from the .NET Framework!

Just like we used events earlier on, we can use IEnumerator and IEnumerable this time.

Refactoring our code to use these, results in the following classes remaining:

IEnumerable and IEnumerator

As you can see, there is no more LegionIterator either, since List provides a GetEnumerator method itself, which we simply call.

Time to test all this code we just wrote and try it out.

Testing IEnumerable and IEnumerator

I've uploaded the solution again. Since this was quite a long article, have a look at the code, I've placed the code for each step in seperate folders so you can compare the changes between steps.

Some additional information on the Iterator Pattern:

 

Time for yet another pattern, the Template Method Pattern. Have a look at all the other patterns in the series as well.

The definition: "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's structure."

Let's add an additional requirement to our game. We need different types of renderers for our GUI, the main screen is in 3D, while the map is displayed in 2D.

Both layouts follow a specific drawing order. 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 overlap the units, which we don't want.

We'll start by creating a new base class for our renderers, with some abstract methods which make up the algorithm of drawing the screen.

Base Class

As you can see, there are two non-abstract methods. DrawBorder() which is common functionality for every render and RenderScreen() which is actually a Template Method.

The Template Method defines the steps used in the algorithm, without actually implementing the steps itself.

Template Method

As you can see from the comments, with the perfect implementation, RenderScreen() should be a method which can't be overridden by child classes. C# doesn't support this however.

When we create our two renderers and have the discipline to not hide RenderScreen(), the class diagram for the Template Method Pattern looks like this:

Class Diagram Template Method Pattern

If we test this code, we notice that the order of rendering a screen is the same, but that each engine implements the steps differently, or not at all.

Testing Template Method Pattern

And that's the Template Method Pattern! I've uploaded the solution again to have a look at.

Some additional information on the Template Method Pattern:

 
Deze post is geïmporteerd van de oude blog en is nog niet geconverteerd naar de nieuwe syntax.
Today I'm going to tell you a little story about me. I think of myself as your typical description of a geek.

Passionate about all things technological, eager to find out how the inner details work together, a movie and music lover, and spending too much time behind a computer.

Having all those feats, over the course of twenty years, result in getting out of touch with the what interests the large part of the population.

I don't care about soccer, drinking, going out or making a complete fool out of myself. I can talk for hours about some architecture however, or about techy pranks.

But you know what? My surroundings don't have a clue what I'm talking about, usually ending up in me not bothering anymore. Same for taste of humor, I love the dry British kind, and everyone I know hates it.

This isn't some sort of self-pity post however. I'm fine with making conversation, but most of the time it's forced, and I constantly have to fight the analytical part of my mind to not interfere and kill the conversation.

That being said, I'd like to meet some other geeks from around the world to have a chat with, the international developer community.

Do you sometimes have the same feelings? Would you like to meet someone new? Talk about some random IT thing, or just about your life to a fellow geek?

Contact me! Tell me something about you, where are you from, how old are you, what do you do, some story. Please? :)


Writing all these articles is fun, but having dialogues is a lot more stimulating.

I hope to hear from you! :)


(Yeah, non-geeks can mail too, if you have some interest in IT or aren't bored by someone talking about it :))
 

Time for another, simple, design pattern. The Facade Pattern.

I'm going to need a break soon, getting a bit burned out, which never is a good thing.

Anyway, the definition of today's pattern: "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."

The hardest part of writing articles for this series isn't so much understanding the patterns itself, but coming up with examples with somewhat make sense in my gaming example. So, please forgive me if they sometimes are a bit far fetched, like today ;)

Let's say we have some complex subsystem which handles everything about storage. Some classes for our CD drive, some for our hard disk, memory and much more.

Complex Subsystem

If we need to load a new map, 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.

Or, we could also create a new class, which defines some more high-level operations such as LoadMap(), which takes care of dealing with the subsystem.

This way, our clients can use a simple interface, but if they really need to, can still go straight to the subsystem classes themselves, as opposed to the Adapter Pattern, where you only talked to the Adapter.

Facade Class

And that's it really, Facade and Adapter are very alike, and both very simple.

Let's have a look at the full diagram, and image the subsystem contains a lot more classes than I drew :)

Facade Pattern Class Diagram

Time to test it and have our client use the StorageFacade directly, instead of the subsystem.

Testing Facade Pattern

I've uploaded the solution again, worth a look.

In my opinion, the Facade Pattern is a helper pattern to make your code easier to use and more user-friendly, other developers being the user.

Some additional information on the Facade Pattern: