Monthly Archives: February 2014

Pattern of the Week: Abstract Factory

This is the fifth in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Creational

This week’s pattern is the Abstract Factory pattern. To explain this, we must first understand the factory class.

Factories create things, plain and simple. Whether we’re talking about software development or retail, that is what they do. Factory classes typically look something like this:

The method creates an instance of its favorite implementation of the interface that is returned. Obviously, with a simple code change, you could swap out “ConcreteSomething” for “SpecialSomething” and your code would still work, assuming of course that those are both implementations of ISomething. This is a central idea of a SOLID principle, called the Liskov Substitution Principle. Basically, we should be able to swap out an implementation of an interface without breaking our code, or changing the behavior of the application, i.e., post-conditions of using the interface should be the same no matter the implementation that we use. Now that we’ve talked about Factories and Barbara Liskov, let’s go back to the pattern at hand.

The Abstract Factory pattern can be used when you want to define different versions of the same family of interfaces in your application. You know that you need certain objects that implement certain interfaces, but you might need to swap out which ones you use depending on a number of factors (which OS, database server, etc.). The implementation of certain interfaces that you end up using is completely dependent on what implementation of the factory you’re using. Here’s an abstract factory interface, which creates clothes (kind of like a real factory!):

This interface defines two methods: CreateShirt(), and CreatePants(). These methods return IShirt and IPants respectively. Let’s look at those interfaces:

Alright, so we now have defined our interfaces that we will use in the factory. So what do we do next? Well, an interface is fairly useless without implementations, so let’s create some. Here is a DressClothesFactory:

Simple enough, right? The factory defines the CreateShirt() method as returning a DressShirt, which is an implementation of IShirt, and it defines CreatePants() as returning DressPants, which is an implementation of IPants. We could also define a CasualClothesFactory which would return a T-Shirt and Jeans respectively.

The real power of this is when we define a method or class that takes an abstract factory implementation, and uses it to instantiate the classes that it needs. For example, let’s look at the ShowWhatAmIWearingToday() method:

We know ahead of time that we need to get a shirt and get pants, but we don’t really care if it’s a casual day or a dress-up day. We still need those two things no matter what, the only difference is what specific family of IShirt/IPants we’re using.

This is pretty much all there is to this pattern. If you need additional help, please take a look at the full source code below, or feel free to comment, and I’ll respond directly.

Visit next week for an explanation of the Proxy pattern.

View Sample Code

Pattern of the Week: Template Method

This is the fourth in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Behavioral

This week’s pattern is the Template Method pattern. This pattern allows you to define a set of algorithms that follow the same procedure, but that might have certain parts that differ. For this pattern, I’m borrowing heavily from my post on the Strategy Pattern, so if you haven’t read it yet, you should read that one first.

Alright, let’s look at a template method:

This method, called Attack(), defines a basic algorithm of attack. First, we print out the warrior’s name (as a battle cry?), then we get that warrior’s weapon of choice, and finally, we use the weapon. Here’s the rest of the Warrior abstract class:

We use this abstract Warrior class to define specific types of Warriors, like this one:

As you can see, the derived class “fills in the blanks” of the template method, by defining what the GetWarriorName() and GetWeaponOfChoice() methods do. We’re filling in the blanks of the template by using inheritance. When we call the Attack() method, the methods defined in the derived class are called, completing the algorithm for the type of Warrior we’re using.

This is pretty much all there is to the Template Method pattern. If you need additional help, please take a look at the full source code below, or feel free to comment, and I’ll respond directly.

Visit next week for an explanation of the Abstract Factory pattern.

View Sample Code

Pattern of the Week: Strategy

This is the third in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Behavioral
Difficulty: Beginner

This week’s pattern is the Strategy pattern. This pattern can be used when you have a set of similar algorithms. The easiest way to explain it is with an example, so let’s look at the following class:

Here we have a class that represents a Warrior. There is a primary weapon that is passed into the constructor. The warrior has a method called Attack, which uses that weapon. Let’s look at the IWeapon interface.

This interface has just one method, Use(). When the Warrior needs to attack, he needs to be able to use his weapon. Seems pretty straightforward, right? No matter what kind of weapon that the warrior has, he needs to use that weapon in order to attack. The only difference between each type of weapon is how the warrior uses it. This is the essence of the Strategy pattern. It allows the ability to change the how without changing the what. Let’s take a look at the implementations of the IWeapon interface.

For example’s sake, I didn’t elaborate on how the warrior would use each weapon, but obviously there are huge differences. One slashes with a sword, fires a shotgun, and throws a grenade. However, how the warrior approaches using a weapon is the same: he thinks, “I need to use my weapon”, and then he does whatever it takes to do that.

So, how do we use this? It’s pretty simple. If we want a Warrior who uses a Sword, we do this:

We would do the same thing for all of the other weapon types too.

This pattern may look very familiar to those of us who use Dependency Injection, or more specifically, Constructor Injection. Constructor Injection is probably the most widely used example of the Strategy pattern, but there are other things you can use it for as well. An example that comes to mind is that you could implement data access as a strategy pattern, then pass in the proper implementation based on the database server type that you are using.

That’s all! Visit next week for an explanation of the Template Method pattern.

View Sample Code

Pattern of the Week: Decorator

This is the second in a (hopefully) long series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Structural
Difficulty: Beginner

This week’s “Pattern of the Week” is the Decorator pattern. To explain this pattern, I’m going to start with an explanation of the Open/Closed Principle. The Open/Closed Principle is one of the five “SOLID” principles outlined by Robert C. Martin in his works. The principle states that a class should be open for extension, but closed for modification. What does this mean? It’s actually pretty simple. We shouldn’t change the behavior of a class after it has been defined, and we should be able to extend the class by various means to add functionality. One of the ways to extend a class without modifying it is the Decorator pattern. Without further ado, here’s a class:

Well, that’s a pretty simple class. It implements the following interface:

Nothing revolutionary there. We’ve represented a pretty basic person. So, let’s say we want to print out the information on the console. Here’s one way to do it:

Since this only deals with the Person class, maybe we should add it to the Person class, as a Print method. But wait, wouldn’t that be modifying the class to extend it? Yes. So, we shouldn’t do that. Worse, it would also be violating another SOLID principle: The Single Responsibility Principle. This class would have the responsibility to keep Person information, as well as the responsibility to print it out to the console. Well, we don’t want to break two SOLID principles, so let’s try something using the Decorator pattern instead. We’ll create the following class:

Now, there are a couple of important notes about the PrintablePerson class. First of all, you’ll notice that it implements the same interface as the Person class. It also adds a method called Print. Finally, it takes any implementation of IPerson in the constructor, then hands off all calls to IPerson properties and methods to that class. So, how does this help us?

Well, we can now add printing functionality to any IPerson implementation, without changing the class itself. This new class also has only one responsibility: printing. That covers both the Single Responsibility Principle and the Open/Closed Principle. So, let’s look at this in action:

By decorating the Person class in the above code, we were able to extend the class, without actually modifying the original class. This is incredibly powerful. By using this technique, you can keep your classes simple, and make sure that they only have one responsibility. You can also avoid changing the code in a class that you know is working, so you don’t have to worry as much about introducing bugs. (You should still test though!)

You may be asking yourself, “that’s good and all, but when do I use it?” Well, there are countless ways to use the pattern. Microsoft actually uses the pattern fairly heavily in the .NET Framework, mainly with the System.IO classes. You could use it to add logging to a class that doesn’t have it built in. You could use it to handle exceptions from a class that doesn’t handle them. Again, the possibilities are nearly endless.

That’s all! Visit next week for an explanation of the Strategy pattern.

View Sample Code