Category Archives: Pattern of the Week

Pattern of the Week: Builder

This post is part of 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 called the Builder pattern. The builder pattern is a common way to create an object, using methods and properties to set up exactly the kind of object you want, then calling a Build() method to actually create the object. Let’s look at an interface for a builder object:

This interface has a couple properties, ShirtColor and ShirtSize, and a method called Build. Let’s look at ShirtBuilder, the concrete implementation of this interface:

This class creates a Shirt object, which implements the IShirt interface. This interface and class are incredibly simple, so we don’t need to go over them here. Please look at the source code if you’re curious.

Now that we have the builder ready to create shirts, what do we need to do now? Let’s use it! A builder is also really easy to use.

The shirt variable above now has a fully initialized Shirt object with all of the parameters that you wanted. It’s ready to use.

The question is: when should I use this? You should use this pattern when you need to specify a lot of details about the object you’re creating. If you just need an object, with maybe one or two properties that need initialized, you should consider using the Abstract Factory pattern or a simple copy constructor instead. If there are a ton of things that you need to set on the object, Builder is the way to go.

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 another pattern.

View Sample Code

Pattern of the Week: Prototype

This is the seventh 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 called the Prototype pattern. This pattern is used when you need to create exact copies of objects. Let’s look at our example Prototype class:

This StreetSign class has two properties – Text and Shape, and a method called Clone. The prototype pattern is fully represented by the “Clone” method. Basically, the Clone method should be implemented so that it returns an exact copy of the object on which it is called.

There are many ways to implement this pattern. A most ideal way would be if you could have the method reflect over the entire object. This would mean that you could add properties to the class without having to change the Clone method. The simplest way is the way that I implemented it in the code sample. A new instance is created and the properties are set on the new object (in this case, via the constructor). Either way is valid.

It should also be noted that there is a method on System.Object in .NET called MemberwiseClone, which essentially implements the Prototype pattern. The only thing about this method is that it creates a shallow copy, so if you have objects within your objects, those won’t be copied. Instead, the same instances of those sub-objects will be referenced by the clones.

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 another pattern.

View Sample Code

Pattern of the Week: Proxy

This is the sixth 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: Structural

This week’s pattern is called the Proxy pattern. This pattern is primarily used to add security or to implement caching for objects. For my example, I’ll be adding security to this class:

This is a pretty simple class, which implements the following interface:

Now, suppose I want to make sure that not everyone has access to the GetStrings method. Well, I could modify the GetStrings method itself, and add some complex code to check a user’s permissions, or I could implement a Proxy to do that for me. The main benefit to using this approach is that I don’t overly complicate GetStrings, and I can separate these two concerns (permissions and data access). Here’s my Proxy class:

The proxy implements the same interface as the original class. This means that you should be able to swap the proxy for the original object with minimal code changes. So how does this all work? Basically, we would use the Proxy to access the object, and if the user doesn’t have access (which we’re not checking here), a SecurityException will be thrown, preventing access to the underlying resource. Obviously, in a real-world use of this pattern, you would actually check the user’s permissions in the ValidateAccess method (and always remember to default to least privilege on errors).

You may notice that this pattern is fairly similar to the Decorator pattern. The difference between the two, as far as I can tell, is that the Proxy actually owns the object that it is adding functionality to (it creates it), while the Decorator has the object passed in as a parameter in the constructor.

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 Prototype pattern.

View Sample Code

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

Pattern of the Week: Singleton

This is the first 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: Creational
Difficulty: Beginner

Singleton. It is probably the least complicated of all design patterns, yet it can be confusing for beginners. In this post, I will attempt to explain exactly how to create a Singleton, talk about common implementation problems, and provide some sample code so you can see it in action.

The basic idea of a Singleton is simple. I only want one of some object. Well, that’s easy, right? Don’t create more than one. Looks like my work here is done. Well, what if I want to ensure that there is only one instance of a certain class ever created while my application is running? That’s where Singleton comes in. Singleton basically protects you from creating more than one of something. It also only creates the instance the first time you use it, i.e., lazy initialization. Here’s a basic implementation:

The above code is pretty much the simplest way to create a Singleton. It also isn’t thread-safe, and it isn’t very useful (no properties, members, etc.). Before we go on to that, let’s explain what we’re looking at. First, you’ll notice that the class has a private constructor. This is due to the fact that we don’t want people to just do this:

You’ll also notice a private, static variable on the class called _instance. This variable is what actually holds the Singleton instance. Finally, you’ll notice the Instance property. This is where all the work is done. The getter first checks to see if there is already an instance, and if there isn’t, it creates one. Then, it simply returns the instance. This ensures that there is only one.

Now, this is great, right? Not really. What if your application is multi-threaded? Meaning, two threads accessing the Instance property at the same time? Well, thread 1 will hit the if statement, and say, “I need to create an instance.” Maybe thread 2 will hit that same if statement before the instance is created, and it’ll say, “I need to create an instance.” So, it’s actually possible to end up with two threads with two different instances of Singleton. Fixing this is simple though. See the below corrected code:

I’ve added a static lock object that will prevent more than one thread from going through the instantiate + return code. This means that if the threads reach the code at around the same time, the later one will have to wait. So, looks like we’ve solved all the problems with Singleton. Wait, what if I create a derived class? You can’t create a derived class outside of the Singleton class, since the constructor is private, but what if you create one inside of Singleton?

Then, somewhere in your code, say:

Guess what? You’ve just created two instances of a Singleton class! How do we fix it? Simple. Add the sealed modifier on to the Singleton class. Sealed classes cannot be derived. Here’s our final code:

To make this useful, you would simply add properties to the Singleton class, then access them like this:

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

View Sample Code