Welcome back for another episode in the pattern series! This will also be the last article about Design Patterns, since I've finished reading the Head First Design Patterns book :)

It's been a very interesting journey, lots of new patterns learned, lots of knowledge gained, and now it's time to apply them in real projects.

As a summary, the overview of all articles about patterns, including the one we're going to see today:

Let's get started! Make sure you're seated comfortable, it's going to be a long one today!

The definiton, as usual: "Provide a surrogate or placeholder for another object to control access to it."

A new request popped up, we need to add in a multiplayer option in our game, featuring a Lobby where users can get in touch with each other.

This lobby is going to be running on another machine, or in our case, just another console application to illustrate it.

First of all, we're going to start by adding an interface ILobby to define our lobby.

ILobby Interface

We'll place this interface in a seperate library, to better illustrate the Proxy Pattern later on. This way you can clearly see on which machine a specific piece of code is located.

Time to create our actual Lobby implementation!

As mentioned before, we will create this in a seperate project to clearly show the code for the Lobby is not located on the same machine as our main client.

Lobby Implementation

A very simple Lobby implementation, containing nothing more than a List<string> of Users.

At this stage, we can have our Lobby on one machine, but how do we add users to it from another machine?

This is where the Proxy Pattern comes looking!

Just to make one thing clear, the Proxy pattern comes in many different shapes, we're using it to give a client access to a remote object, by means of a placeholder, reminds you of the definition, doesn't it?

In our case, it's called a 'remote proxy', there is also a 'virtual proxy', a 'protection proxy' and more.

A virtual proxy can for example serve as a placeholder for an object which is expensive to create, if you want to retrieve an image over the internet, you could display an icon via a proxy while the real image is loading in the background.

So, let's create this placeholder on the client side.

LobbyProxy Implementation

By placing a reference to our previously created ILobby, this proxy allows our client to work with, what it believes to be, a real lobby object.

In reality however, their is no Lobby implementation in our client code at all, it is merely a placeholder which implements the correct interface.

You might have noticed the notion of a Socket already :)

Our proxy object might implement the correct ILobby interface, if we want it working, we will eventually need to call our real Lobby object.

In a first step this is done using sockets to connect to the server and communicate with the real object.

Before you go screaming .NET Remoting, hold your horses! This is meant to illustrate what is going on behind the scenes with a remote proxy.

When you're coming from the Java world, you might have heard people mentioning a Skeleton.

This is not something creepy, but simply a class on the server side which intercepts call from the Proxy, talks to the real object and sends the results back.

Here's a small part of our Skeleton code:

Proxy and Skeleton Code

As you can see, the Proxy talks to the Skeleton, which talks to the Real Object, after which it sends the response back over the wire.

When we put all of this in action, we see the following happening:

Testing Proxy Pattern

Our main client talked to a remote Lobby and registered some users, great!

Now that we've seen how a proxy serves as a placeholder, it's time to clean this code and get rid of all the socket stuff.

Just a note, all the socket stuff in the project is highly unstable and not meant for production! Don't use it!! It's only meant for demo purposes :)

Let's work on the server side first by removing the Skeleton code, referencing System.Runtime.Remoting, and letting our Lobby class inherit MarshalByRefObject.

Lobby Remoting Implementation

Last step needed for our server is to expose the Lobby object through Remoting, which is nothing more than having something like our previous Skeleton code hidden behind the scenes.

Exposing Lobby Remoting

The only thing left to do now is to remove the Proxy class from our main project, and use Remoting to get an instance of ILobby, which acts as a proxy behind the scenes.

Utilizing Remoting Proxy

Resulting output when we run this version? Exactly the same! But a lot less work to implement :)

And that's it, another pattern in our heads!

I've uploaded the solution again to have a look at. When you run it, make sure your run the GameServer first, unblock it on your Windows Firewall, and then run the Proxy project.

Well, that's it, the last part of my series. I hope you liked them and learned a lot from it. Be sure to keep on visiting for some other tech subjects coming up soon.

You can always subscribe to the RSS feed to stay informed.

Thanks to the people who were generous enough to donate a little bit after reading some of these articles! (If you'd like to donate, simply use the PayPal button on the left :))

See you soon!

Some additional information on the Proxy Pattern:

 

It's been a while again, but it's time for another pattern. Today we'll look at the State Pattern.

First of all, the definition: "Allow an object to alter its behavior when its internal state changes. The object will appear to change its class."

An additional request has surfaced today, we need to keep track if a unit is alive or dead and let it respond differently based on the state it is in.

Initially we solved this by introducing a new enum called UnitState and adding lots of switch() statements to our code.

Initial State Implementation

In the long run however, this would mean we have to keep on going into those statements whenever a new state needs to get added, which isn't exactly following the Open/Closed Principle we talked about.

Let's refactor this and introduce a new interface called IUnitState.

State Interface

Instead of using an enum, we're going to introduce two new classes, which implement IUnitState to represent our different states.

Concrete States

By seperating the logic for different states in different classes, we can add a new state easily, by simply creating a new class, and we keep our code base structured.

For example, the most simple state looks like this:

State Implementation

When we pull all of this together we get the following class diagram, illustrating two concrete states and the state interface.

State Pattern Class Diagram

To the outside, whenever the internal state changes, it looks like the object, GameUnit, changed it's type because a different concrete state is providing an implementation for the actions.

When we test this code, we can see the behaviour of internal state changing after the first Kill() command.

State Pattern Class Diagram

I realize this isn't the best example given to illustrate the State Pattern, I'm not quite that happy with it, stretching the game example like that, sometimes it works out, sometimes it feels a little forced, like today. I hope it made sense, be sure to check out the sites below for some other examples as well.

I've uploaded the solution again so you can have a look.

Some additional information on the State Pattern:

 

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:

 

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:

 

We've seen quite a few patterns so far, and I'm glad so many people like them.

They turned out to be the most popular posts I've ever written when it comes to development. Thanks! :)

A little overview for the late joiners:

Today we'll have a look at the Adapter Pattern.

As usual, the definition: "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."

To continue on our little game, we received a third party library from another team, containing some buildings to include in our game.

The developers of this library didn't work with IBuildings however, but call it a Structure, making all of our code which interacts with IBuilding unusable.

If we look at the definition, we can see the Adapter Pattern is the perfect solution for this, since we need to convert the interface of the third party Structure into the IBuilding we expect, so that they can work together as if their interface was compatible.

Let's have a look on how their interface looks like first.

Third Party Library - Adaptee

There are some differences in the logic used in their implementation. We both have a Description, but the way we manage Power consumption is totally different.

Time to adapt their interface to the one we expect.

We'll do this by creating a new class, a so called adapter, which implements the IBuilding interface, since we expect that one, and which uses composition to encapsulate a Structure.

Adapter Class

As you can see, our Adapter is actually behaving as an IBuilding to the rest of our code, adapting the calls to our interface into the third party their interface.

And that's it really! The easiest way I remember this pattern is by thinking of electrical adapters, changing the socket from US to UK, or transforming the voltages.

Time to have a look at the full diagram, with the official names written against it again:

Adapter Pattern Class Diagram

Let's also write some test code to see the Adapter Pattern in action.

Testing Adapter Pattern

We can re-use all of our existing code with the new Structures, since it's behaving like an IBuilding right now.

I've uploaded the solution again to have a look at.

Feel free to leave any feedback.

Some additional information on the Adapter Pattern:

 

What's a lonely geek to do late in the evening? Write about the Command Pattern of course...

Let's start with the definition: "Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations."

And now, time for the spec I just made up: Our UI has three buttons at the bottom of the screen, which contain various actions. These actions are different depending on the selected item however. We need to implement this piece of UI code, without it having any knowledge of our game units.

How would we approach this? Let's say these buttons are nothing more than placeholders, to be filled with real buttons whenever a unit is selected. Our game engine will respond to a selected event and create and pass on the real buttons to our UI code.

So, our UI code will only need to know about one thing, a button. Let's create an interface for this type of button, and coincidentally name it ICommand :)

Command Interface

We'll code our UI code against the ICommand, respecting to program against an interface and not an implementation.

At the end, we'll need some real implementations as well however. So let's create some "buttons", which I'll call Commands from now on.

Right now we only have two types of items, GameUnits and IBuildings. Each Command will perform an action against one of these, encapsulating the object through composition.

For this example, we can make a GameUnit turn Aggressive, Normal and Suicidal. We can also power buildings on and off.

Command Objects

Notice these Commands themselves are written against interfaces as well, our good habits are already starting to pay off.

The NoCommand is a little tricky, it's just a dummy object, which sometimes is called a [Null Object(http://en.wikipedia.org/wiki/NullObjectpattern "Wikipedia - Null Object Pattern") as well. It's being used for buttons which don't do anything, basically their default value.

It's time to create our UI code, the GameControls class. This class will contain the three buttons, ICommands, and helper methods to assign real buttons into the placeholder slots, as well as triggering button clicks.

Additionally, there's another requirement which has surfaced. We want to be able to undo our last action, whenever possible, can't undo suicide ;)

We'll accomplish this by storing the last ICommand, and when an undo action is needed, call the Undo() method on it, since each command provides the exact opposite of Execute() in it's Undo() method.

Invoker Object

That's all the code that was needed to implement the Command Pattern actually.

Our GameControls class has no idea GameUnit or IBuilding exists, it's totally decoupled from them.

By using Command objects, we can treat them as little blocks which can be stored in a queue for multiple level undo, we can let several threads pop commands of a queue to process them in parallel, and much more.

Let's have a look at the full diagram, with the official names written on them as well.

Command Pattern

Time to put our code into action and test it.

Let's imagine we have a full blown engine, and when a unit is selected, various events get fired, resulting in the creation of the correct ICommand objects, being passed to our GameControls UI code, which causes buttons to be displayed on screen. We'll also simulate a click on the various buttons and the undo button.

Testing Command Pattern

That's it! I've uploaded the solution for the Command Pattern so you can have a look at the code of the Command Objects and the details of the GameControls.

Questions? Feedback? Comment!!

Some additional information on the Command pattern:

 

A little follow up from yesterday'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:

Generic Singleton Pattern

Using Reflection, the private constructor is called to create an instance of the class.

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.

I've updated yesterday's solution to contain this new code as well, have a look.

I'd like this post to draw some attention from CLR guru's to have a look at the implementation and point out possible problems and how to solve them.

 

Today we'll have a look at a well known pattern, the Singleton Pattern. Most people have already heard about this one.

The definition: "Ensure a class has only one instance and provide a global point of access to it."

Why would you want to only have one instance of a class?

Well, you could have one Configuration class for example, which reads some configuration settings at runtime, after which they remain available to your application.

It makes sense to only have one instance of this class, since having multiple could cause you to suddenly end up with different configuration settings.

Now, there are different Singleton Pattern implementations out there, which makes it interesting to have a look at it anyway.

First of all, let's look at the basics of how a Singleton works. Since we're working with our game example, a good singleton would be a reference to our hardware, the GraphicsCard, we should have only one instance of it, who knows what would happen if we start mixing up various instances :)

To make sure there is only one instance of a certain class, we let that class itself manage it's instantiation, instead of creating it ourselves using the new() operator.

Preventing others from calling new() on our class is done by making the constructor private. This way nobody can instantiate the class directly.

But how do we get an instance back then?

We provide a static method in the class itself, returning an instance of itself. By doing this, we can create one instance upon the first request and keep returning the same instance upon further requests.

This is also a form of lazy loading, since it only gets created when it is requested for the first time.

Basic Singleton

Where's the catch you might ask? Multi-threading! This simple implementation of a Singleton is not thread-safe!

It is possible for multiple threads to both execute the null check together, both evaluate it to true, since there is no instance yet, and then both threads create an instance, ending up with multiple instances instead of one.

Luckily, there's a solution. I'll cut straight to the point and give the thread-safe, lazy loading version. There are other thread-safe implementations out there, which you can read more about at Implementing the Singleton Pattern in C#.

Thread-Safe Singleton

As you can see, the actual instance is held inside a private sealed nested class, which is inside the GraphicsCard class. When the Instance property is called for the first time, it will instantiate a GraphicsCard in a thread-safe way, thanks to the Nested class, and upon subsequent requests, the same instance will be returned.

It's elegant, and doesn't use any special language keywords like lock() in C# or synchronize in Java.

I think it's quite easy to set up a Singleton like this, once you've done it once, you can do it everywhere.

With C# and generics however, we can be even more lazy, which is why I tried out throwing the Singleton Pattern into the following code.

Generic Thread-Safe Singleton

Now the only thing we need to do when we want to create a singleton is create a class, inheriting from Singleton passing the class itself in as the generic T.

The usage of both classes is identical afterwards, as you can see from this small snippet:

Singleton Usage

That's it, one of the easiest to understand patterns conceptually, but with some common pitfalls when implementing it.

There is one big issue bothering me with the generics approach however, hopefully someone can help me out on this, in an elegant way.

As it is coded right now, you can do new GraphicsCardGeneric(), which is something I don't want, since you run the risk of ending up with multiple instances again.

I can't add a private constructor however, since the generics break down then, requiring a public parameterless constructor to do new T() inside the Nested class.

If anyone has a nice solution to get around this, while keeping generics, please comment and let me know. Personally I feel safer using the non-generics solution for now, since it locks down new() instantiation of the Singleton.

As usual, the project is available again to look at for further detail.

Some additional information on the Singleton pattern:

 

Time to continue from yesterday's Factory Method Pattern by exploring the Abstract Factory Pattern.

Right now, we have created separate classes for both factions' units (CyborgCommando and Ghostalker). Let's change this so each faction has identical base classes containing logic, but slightly different configuration depending on the faction they belong to.

We'll do this by implementing the Abstract Factory Pattern. I always mix this one up with the Factory Method Pattern, but it finally got through to me while writing the code for this post.

With Factory Method, we have an abstract base class containing logic and calling our abstract factory methods, which return a real implementation via subclasses.

While the Abstract Factory is passed into an object where it is used as composition, and the real factory is supplied at runtime, decoupling the usage of our factory from the real implementation.

Anyway, time for the definition and then some code to make everything clear. "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

First of all, let's get rid of our faction specific units and replace them by generic ones.

Generic Game Units

You'll notice the GameUnit has been given a new constructor, an abstract class containing only abstract methods.

This class forms the definition of the Abstract Factory Pattern, it's an interface to create related objects without specifying a concrete class.

Abstract Factory Class

Our GameUnit class is not working with a concrete type, but with an interface, decoupling it from a real faction implementation.

We aren't much with just this interface, so let's create an implementation.

Factory Implementation

As you can see, the classes we used to illustrate the Strategy Pattern have been moved to this factory implementation, which means our GameUnit and all other unit implementations are now working with interfaces rather than concrete implementations.

Another thing left to do, is to let the units get their information from the abstract factory.

Interrogating the Abstract Factory

All that is left, is a small change to our two InfantryFactories to pass in the correct FactionDetailsFactory to each unit, and our test case is ready to run again, without having to change it.

Providing a Factory Implementation

You might wonder what the IBuilding interface is suddenly doing there, well, I cleaned the code a bit up and decided to place everything in separate files as it should. Never done it before to keep it simple for these articles, but I didn't like the code adding up.

With the Abstract Factory Pattern implemented, our results looks like this:

Abstract Factory Pattern

So, here's the uploaded solution again, changed quite a bit since last time, take your time to have a look at it.

As usual, feedback is much appreciated.

Some additional information on the Abstract Factory pattern:

 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
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'm currently reading deals with both factory patterns, Factory Method and Abstract Factory, in one chapter, but I'm going to write an article on each to limit the length.

First of all, the definition: "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."

Today we were given specs to add a building to our game. This building will create infantry units, set their behaviour to a specific setting and send them to a given waypoint after creation.

We start with a simplistic approach of creating an InfantryFactory class, which represents a building and contains a building-specific waypoint and unit behaviour setting to be given to new units.

Simple Unit Factory Building

It does the job, a specific unit is created based on a runtime parameter, it is given its behaviour and sent to a specific destination.

However, when we need to add new units, we need to open up this class every time again and change inside of it, which violates the Open/Closed Principle we talked about last time.

Let's isolate what changes and move it to its own method, just to illustrate we understand the part that is most subject to change.

Isolating Change

Since the CreateUnit method is still inside the same class, we still have a problem. The BuildUnit method is a fine piece of code now however, it works with GameUnit objects instead of actual implementations.

Once this code passes our quality assurance it can be extended as much as wanted without having to modify it. Let's get this entire class to meet our quality standards now by implementing the Factory Method.

Our InfantryFactory class forms a nice base for creating units and performing various logic, let's lock it down for modification by making it abstract and throwing the CreateUnit implementation out as well.

To throw its implementation out, we are going to define CreateUnit as an abstract method, forcing subclasses to implement it. Let's create two factories for both our factions.

Factory Method Pattern

As you can see, I've taken the liberty to add some more units since last time, to illustrate how our two factories decide which class to instantiate in the CreateUnit method. Which is exactly what the Factory Method definition describes.

We defined an interface for creating an object, the abstract CreateUnit method, and let the subclasses, Barracks and HandOfNod, decide which class to instantiate. We made our InfantryFactory open for extension and closed for modification!

Factory Method Pattern - Code

When we test this code, you can see our objects are always using abstract classes or interfaces (an abstract class is also called an interface sometimes, in the sense of the English language, not in the C# keyword).

Factory Method Test Case

The result after all this coding is this little output, and the fact that we learned another pattern, the Factory Method.

Factory Method Test Case Output

I've uploaded the solution again. If you have any questions or feedback, please comment.

Some additional information on the Factory Method pattern:
 

Following up on the Observer/Event Pattern, it's time for the third pattern, the Decorator Pattern.

The definition: "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."

Continuing on our little game, let's say we are able to create buildings and have just an IBuilding interface and one building.

Simple Building

Each building has a description and a given power usage cost, which is simply hardcoded in the class right now.

After a while, our boss hired an external company to take over development with regards to the buildings and tasked them with making buildings upgradeable.

The first approach they took was too simply add new building classes to the game, for each possible upgrade.

Class Explosion

This however leads to an infinite amount of possibilities and a nightmare to maintain.

If we look at the definition of the Decorator Pattern, it seems to offer a good alternative to all this inheriting to add in new functionality.

Also, adding additional responsibilities dynamically means we don't have to change the code of the IBuilding and NormalBuilding either. By doing this we are honoring the Open/Closed Principle, which says "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

How are we going to add these additional things dynamically? We'll decorate our initial NormalBuilding with upgrades, giving us flexibility to equip a building with any upgrade combination we like.

When we mention decorating, think about wrapping. We are going to wrap an instance of IBuilding in a decorator, acting as a shell around the class, passing calls to our decorator along to the wrapped instance, modifying the results when needed.

It's also possible to chain decorators 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 again and again.

Eventually we'll end up with the following class diagram. Note, the WrappedBuilding has a protected getter and a private setter.

Decorator Pattern

Now we have a set of buildings, which implement IBuilding and one decorator base class, BuildingUpgradeDecorator, from which all possible decorations inherit. This decorator class has to implement IBuilding as well, so it can be re-decorated.

With the above classes, it's possible to compose buildings as we desire, as shown below.

Decorator Usage

When we run this code, the call to the Power property is being passed through all decorators to the lowest level, our NormalBuilding, and returned all the way back, getting incremented with the additional power usage for each decorator/upgrade in the mean time.

Decorator Output

I've uploaded the solution again so you can have a look on how the decorator base class and individual decorators are programmed.

Some additional information on the Decorator pattern:

 

Yesterday I described the Observer Pattern and mentioned that the .NET CLR provides this functionality through events and delegates.

Let'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'll replace it by a push notification mechanism.

Push, because we'll pass the required information along to the observers when notifying them, as opposed to pull, where the observers had to extract it themselves from the subject.

Since we'll be pushing out the information, we need a custom class defining which information is interesting. We'll create this by inheriting from the EventArgs class, by doing this it will be very easy to set up an event in the next step.

Custom EventArgs Class

As you can see, this is a very small class, with a descriptive name, containing the new location of our unit.

You can't see it on this diagram, but the NewLocation property only has a public getter, and a private setter, since our observers will only have to extract data from this class.

So, we got our small information holding class, now it's time to change our GameUnit class to get rid of all the logic of maintaining a list of observers and subscription logic.

We'll replace the ISubject logic by an event of the type EventHandler<PositionChangedEventArgs>. By doing this, we expose an event (PositionChanged) to our observers upon which they can subscribe themselves whenever they want as well as unsubscribe when needed.

Observer/Event Pattern

Note that this event is strongly typed, containing a strongly typed information set, making it easy for our observers to get the information they need.

Using this method, we can have a set of EventArgs classes as small data holders, after which subjects can expose events using those custom EventArgs to the outside world, making sending out notifications very easy.

Observers on their side can easily subscribe to any of the events exposed by using a single line of code, and perform their logic (_PositionChanged methods) whenever they get a notification.

Have a look at the the uploaded solution to see the exact syntax of this method. We're using delegates with generics, the += operator and throwing and handling events.

Again, if you have any questions, feel free to leave them behind.

Some additional information on the Observer/Event pattern:

 

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's good to know how it works, since it's used behind the scenes in the .NET CLR when working with events. Besides, better know too much than too little, knowledge is power.

Also, I'm planning to write a separate post after this to go into the C# specific implementation anyway.

First, the definition again: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Let's continue with our example from yesterday, were we made an object model to describe some game characters. The next requirement came in, and we need to display movement of our units on the screen.

Initially, we are given one screen, a big overview of a battle map, where all units are displayed on and move around on.

An easy quick approach 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.

This Move() method would then simply call our BattleMapDisplay class to inform it of its new location.

Quick Hacky Notification

That would work, for now... But what if we want to add in a different type of display?

Let's say we want to add in a OverviewDisplay as our main view. Then we have to go and change our GameUnit class to inform this screen as well. Bad. Let's fix this up a little.

If we look at it from a higher level again, all our displays are doing is observing our game units and acting upon any change in them. So, one display is actually an Observer of our GameUnit, the Subject. And there we have it, our displays have a one-to-many relation with a GameUnit and want to be notified when it changes it state, the Observer Pattern's exact definition. :)

Remember from last time? Program to an interface, not an implementation.

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 common communication interface. Let's create that one by adding two additional interfaces, IObserver and ISubject.

Notification Interfaces

Now that we have our new interfaces, we can change the GameUnit class to hold a collection of IObserver objects. Together with providing two methods for additional observers to subscribe themselves so they can get notifications when the GameUnit changes.

By implementing it this way, we can easily add new displays or other objects to our application, which can easily stay informed about our units as long as they implement the IObserver interface and subscribe themselves with the units.

The GameUnit doesn't care about which kind of object is on the receiving end of the notification, and so won't have to be changed 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.

Observer Pattern

Whenever a GameUnit moves right now, it informs all screens about this, passing itself along so the observers can get information out of the object.

And that's it really, the Observer Pattern isn't all that hard, it's a simple notification mechanism. In a next post I'll talk more about delegates and events to have a look on how the Observer Pattern is implemented in the CLR.

If you have any questions about this pattern, please leave them in the comments, something you want to know, something I overlooked or was unclear about, just ask, it's from having a dialog we learn the most.

As usual, I uploaded the solution I used for this post so you have a detailed look at the code used.

Some additional information on the Observer pattern:

 

The first pattern I want to talk about is the Strategy pattern, which always reminds me about the Command & Conquer games so I'll simply use it as an example :)

First of all, the definition: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

I'm bad at remembering definitions or trying to imagine what they really mean, so let's just go ahead and try to create something and learn as we go, eventually we'll end up implementing the Strategy pattern and you'll 'get it' for the rest of your life, without a definition.

A long time ago, we made a simple strategy game, having only 2 units, a soldier and a tank, both were able to shoot at each other which we implemented as follows:

Simple Class Model

The Shoot() logic is contained in the base GameUnit class, since it's identical for both units. Each unit takes care of drawing itself.

After a while, we receive a request to add in an Engineer, which is a unit used to take over buildings and more importantly, he can't shoot.

If we just added an Engineer class similar to the Soldier one, he would be able to shoot as well, which we don't want. We could for this once just override the Shoot() method for the Engineer and make it empty.

Hiding methods - Maintenance Hell

Can you already see where this is going to end up? Maintenance Nightmare!

Eventually we end up with lots of useless code being repeated for every class which has a different shooting logic, where you have to open up every class to figure out all the available implementations. Let's not implement it like this!

What if we were to get rid of the Shoot() logic in the GameUnit class and make an IShootable interface for the units that can actually shoot?

Interface - Code Duplication

That looks a bit cleaner, but wait! We simply shifted the nightmare, because now the Soldier and Tank have identically the same code in their Shoot() method. This isn't the solution either, let's take a look at what our higher level goal actually is.

We can see the part that changes is how a unit shoots. If we take a closer look at shooting and implementing future classes, it is very possible we'll end up with a class that has a very different shooting algorithm or has upgradeable parts, changing the way it shoots. You could say the way a unit shoots is a behaviour of a unit.

Remember the definition of the Strategy pattern? The shooting behaviour we have just defined is actually an algorithm, while the requirement of units being able to get upgraded implies the behaviours have to be changed at run time, making them interchangeable.

Making things interchangeable usually means having less things hard-coded in your application, which reminds of a great saying: Program to an 'interface', not an 'implementation'.

Let's separate all our shooting logic from our units and create a totally new set of classes defining all possible shooting behaviours.

Behaviour Set - Family of Algorithms

Now it's only a matter of letting our GameUnit use these behaviours. We'll do this by programming against the IShootingBehaviour interface instead of against an implementation. This way we can dynamically replace the behaviour at run time, and have a very flexible programming model towards the future.

Adding a new way of shooting is simply a matter of adding a new class implementing the IShootingBehaviour interface after which all our units could use it.

Strategy Pattern

And that's it! We've implemented the Strategy pattern. We defined a family of algorithms (IShootingBehaviour), we encapsulated each one (NormalShot, CantShoot, ThrowKnifes) and made them interchangeable (ShootingBehaviour property).

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'll see how to set this different, since it's not that pretty doing it in the constructor.

Note that even though we are setting a shooting implementation via the constructor, it is possible to change the way a unit shoots at runtime by setting the ShootingBehaviour property.

I've uploaded the sample project I have used while learning this pattern so you can have a look at the code representing the above diagrams yourself.

Some additional information on the Strategy pattern:

 

It's been a while again, real life issues managed to take over all time... But, I'm regaining ground and winning back some of it ;)

For the first time in years, I've managed to get around reading a real book again. Last week I picked up a copy of Head First Design Patterns and started on it yesterday. As far as I can tell, only read the first chapter so far, it's a great book!

It'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 great story, filled with images to clarify and explain concepts. The images aren't even optional, when you really want to learn, you have to read them to get the full picture.

As a form of learning, I plan to write a blog post about each pattern I finish, explaining it in my own words, so it 'sticks' a lot better for myself as well, helping others at the same time. Stay tuned!