Design Pattern of the day: Factory
Programming is like learning to ski (what a Canadian thing to say!). You learn basics quickly, but it takes years to master.
So you know OOP rules. You can create simple and maybe even more advanced programs. Maybe you even know more than one language already. Where should you head next? One of the directions will be design patterns. Let’s take a closer look to one of the most popular ones: Factory. Ingredients: 1 interface and 4 classes.
There is nothing better than real world examples! So let’s imagine you live in Whistler, BC and you are lucky enough to make 12$/hour in the bike shop (you got a free season pass to bike park though!:)). Everyday you sell bikes in a price range from 200 dollars, to +10 000 for a proper dirty jump monster.
But a bike is a bike, and building and selling every bike is still very similar. So we can create an interface called Bike, and give it just one method — sell, that will take a String — brand of a bike frame, and return nothing (void).
Now think about different bikes you can ride. Let’s say, we want to sell 2 types of bikes: mountain bikes and road bikes. These 2 classes will implement our interface Bike. Let’s create constructors for them with int price. We could pass the price as a parameter in a sell() method, but we want to build a bike with exactly the amount of money the client says he has as a budget, so it’s going to be better for us to have it in the actual object.
In the bike shop we just sell bikes. Where are they built? In the factory! So next step will be creating a BikeFactory class. How does it work? As in every factory, the more money a client has, the better bike he gets.
The last step is going to work : creating an actual BikeShop class with main method. Today we have 2 clients: a rich customer from Vancouver, and a poor guy earning minimum wage but living the dream in Whistler. We don’t know yet what bikes they can buy in their price range. Our factory will make the decision.
First, let’s create a BikeFactory object. Then, call on it a method build(budget), that will return a bike. At that point as you can see, you actually have a bike object in our bike shop, that was created in a factory. Now let’s sell it! Because all our mountain and road bikes implement sell method, let’s call it on our bike objects, passing also a bike frame brand as a String.
As you can see, building bikes and deciding what kind of bike it will be, happens in the Factory — bike Shop is not aware of the process, because it is just a broker. BikeShop refers to bike objects by using common interface Bike, but objects are created in the factory.