Jeremy Shanks
Spread the Knowledge!

The Factory Method Pattern

Definition

Defines an interface for creating an object, but lets subclasses decide which class to instantiate. The Factory Method lets a class defer instantiation to subclasses.

How does it work?

The factory method defers the creation of objects to subclasses. This means that instead of creating your objects in your classes like below, you are are deferring to the factory and letting it give you the concrete object.

Above you will see that we are creating an object and then using that object. The problem with this is, if we were to want to add a new concrete object later on, we would have to come back and change this code. We would have to change the code everywhere else that we were creating this object.

Instead of the above code, we can use the Factory Method Pattern and write code like this.

Notice how we are now relying on this GetObject method to give us the correct object based on our needs. If we were to want to change the ConcreteObject later we would only have to change what gets returned by the GetObject() method and the rest of our code would reflect that change.

Why is this useful?

  • As mentioned above, there is only one place to change the code to add new concrete objects
  • The factory method pattern decouples the creation of an object from its use. This helps us adhere to the dependency inversion principle.
  • You can change the object your code uses at runtime

Example Class Diagram

Example Code

For this example, we are going to mock out a vehicle factory that will give us the correct vehicle.

Note: The sample code is in C#.

First we need to create Vehicle class that all of our vehicles will implement. It will be very simple and only give us a quick description of the Vehicle. Check out the code below.

Now we can create our Creator class. Let’s call it “VehicleCreator”. This will be the class we call to get our vehicle objects.

Lets create a couple of concrete vehicles, car and boat. They will both implement the abstract Vehicle class. They will be very simple and change the description.

Now that we have our concrete vehicles we can create the ConcreteCreator classes that will create our Vehicles and return them. Notice how they implement the VehicleStore we created above.

Now that our Factory Method Pattern is complete, it is time to use it.

Above we are creating two vehicle stores, one for the CarCreator and the other for the BoatCreator. We can then use them to create our vehicles and then get the description.

If you run all of the code above you will see the following:

I know this pattern may seem like overkill for this example and it definitely is but this pattern is very powerful and I recommend you give it a try. I tried to strip this example down to its bare bones for simplicity but imagine if you had a lot of vehicles and those vehicles got created in many places in your code.

I hope you have found this post helpful in learning about the factory method pattern. If so, please share this with your fellow developers so that they too can learn.

The Strategy Pattern

Definition

Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

How does it work?

Think of one of those nice digital cameras with the interchangeable lenses like the one pictured below. You can change the lenses on that camera depending on the type of shot you are taking. Some lenses are better for close ups, while others are better for zooming far away. Either way, you can use the same camera for all of the pictures and all you have to do is change the lense.

This is basically how the Strategy Pattern works except in the example above, the camera is referred to as the Context and the camera lense is referred to as the Strategy. You can use the same context (camera) for multiple interchangeable strategies (lenses).

Why is this useful?

  • It can help us combine similar classes into one and extract the behavior so that it can be interchangeable.
  • We can interchange behavior or strategy even at runtime.
  • The Context class does not need to know how the Strategy works, it just uses the common interface.

Example Class Diagram

 

Example Code

For this example, we are going to mock out a player movement strategy that could be used in a game where a player would need to walk or run.

Note: The sample code is in C#. Now let’s get started.

First we need to create the interface for Stratege. Take another look at the UML Class diagram above for reference if you need to.

Now we will create the two movement behavior classes. Notice that they implement the IMoveStrategy interface that we implemented above.

Now that we have our behaviors, we can implement our player class. Take a close look at how we can change the move strategy at runtime.

Now it’s time to use the player and its strategies.

In the above code, we are creating a new Player and both the Walk and Run Strategies. We are then using the method SetMoveStrategy() to change the behavior of the MovePlayer method. If we wanted to create a new FlyStrategy it would be very easy to do so and the player could then be able to fly along with walking and running.

I hope you have found this post helpful in learning the Strategy Pattern. If so, please share this with your fellow developers so that they too can learn.

The Observer Pattern in C#

Definition

Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.Continue reading

How to Create a Simple Address Book in C#

In today’s tutorial, we are going to make a simple address book in C#. We will see how to create lists and arrays and use them in a real world application such as this simple address book. I am also going to be trying something new with this tutorial where I am asking you to implement what is missing.Continue reading

How to Create a Change Calculator in C#

In this tutorial, I will show you how to create a simple change calculator in C# using Visual Studio. I will show you how to take any dollar amount and calculate exactly how many bills and coins to give back. By the end of this tutorial, you will be able to run your change calculator and calculate the bills and coins (in US dollars) that amount equals.Continue reading

1 2 3 6
>