Design Patterns – Proxy Pattern
Gepost op 2008.08.16 | Reacties (6) | C#, Design Patterns, Technologie
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:
- Long Absence – Design Patterns
- Design Patterns – Strategy Pattern
- Design Patterns – Observer Pattern
- Design Patterns – Observer/Event Pattern
- Design Patterns – Decorator Pattern
- Design Patterns – Factory Method Pattern
- Design Patterns – Abstract Factory Pattern
- Design Patterns – Singleton Pattern
- Design Patterns – Generic Singleton Pattern
- Design Patterns – Command Pattern
- Design Patterns – Adapter Pattern
- Design Patterns – Facade Pattern
- Design Patterns – Template Method Pattern
- Design Patterns – Iterator Pattern
- Design Patterns – Composite Pattern
- Design Patterns – State Pattern
- Design Patterns – Proxy Pattern
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.

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.

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.

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:

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:

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.

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.

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.

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:
Design Patterns – State Pattern
Gepost op 2008.08.08 | Reacties (4) | C#, Design Patterns, Technologie
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.

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.

Instead of using an enum, we’re going to introduce two new classes, which implement IUnitState to represent our different 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:

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

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.

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:
Design Patterns – Composite Pattern
Gepost op 2008.07.27 | Reacties (3) | C#, Design Patterns, Technologie
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.

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.

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.

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

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

Resulting in the following orders:

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:
Design Patterns – Iterator Pattern
Gepost op 2008.07.23 | Reacties (5) | C#, Design Patterns, Technologie
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.

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:

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:

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.

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.

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

We still need to pull out the concrete Eva and Legion classes however. Let’s do this by introducing a new interface, called 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.

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:

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.

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:
Also have a look at this personal post: Wanted: Friends!







