Introduction

When we hear the word Design Pattern, the first question that comes to our mind is, “What are Design Patterns?”Design Patterns are reusable and documented solutions for recurring problems in software development.
Gang of four (GOF) have categorized Design Patterns into 3 categories

Creational

Structural

Behavioral

When I started to learn Design Pattern I found Factory method as a very intriguing pattern. It is one of the most controversial and confused Creational Pattern. There is a alot of confusion in People to understanding this pattern .
First of all let me make all of you clear there is nothing like Factory Pattern (as per GOF design pattern list), GOF has something called Factory Method Pattern. (We will come across with both the terminology later in this stage)

In this article for discussion and explanation purpose I am introducing to you, two fictional characters Alexander (a .NET developer) and Thomas (CEO of an IT institute called Programmer24X7).

Story begins on the day when Thomas contacts Alexander and asks him to take up role of architect in his in-house project called “Course Management System”. We will see how Alexander progresses his knowledge about Factory Method Pattern day by day and how finally he come up with a great solution.

Before you starts reading this article, a small advice from my side, keep some snacks ready besides you, because it’s going to be a weary 6 day story. Basically I am trying to play with your patience. don’t worry just kidding. It’s gonna be fun, you will enjoy reading this article and towards the end of this article you can proudly say “I know Factory Method Pattern”.

Day 1

Alexander (our .NET developer) collects requirements from Thomas (our Programmer24X7 CEO). One of his primary requirements was to build a module which will manage online courses offered in the Programmer24X7 (technical institute).

How Alexander started?

I) The system Alexander is going to develop is Course Management System, so the first logical step was to start creating Course Library.

II) Next step will be creating instance of courses and building the UI – User Interface. Following is the most obvious code every programmer thinks about and even Alexander did the same.

Final step – demonstration

Since module was ready, Alexander demonstrated the same to Thomas, and Thomas felt great about the architecture. Alexander’s efforts were well appreciated but, it all didn’t end there. He then took the requirement to next logical level where he shared his further plan with regards to the application. He said,

He is planning to add new online courses like C++, VC++ etc. and would like to stop few courses in future.

In future In Programmer24X7 offline courses are going to be conducted, so make sure to make everything reusable.

Thomas requested Alexander to make changes as per this advance scope. Well it came to Alexander as a Big Surprise

It was like out of the frying pan but into the fire situation for Alexander.

“Adding a new course means”, open the existing UI Code existing logic (add some more switch cases and in future remove some existing case.)

Consider a situation of builder, who is asked to add one more floor between 1st and 2nd floor after the building construction is over taking care that building doesn’t collapse.

Problem with the Approach 1

SOLID principle OCP (Open Closed Principle) will be violated when Course library modifies. (OCP says, software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification)

Reusing the same (Course creation) logic in another UI is not possible.

What Alexander learnt?

Alexander realized an important thing about software development and learnt a great lesson “Changes are integral part of development and system should developed in such a way that it can be easily adapted to such changes without modifying existing tested sections.”

Isn’t it funny, change the system but don’t change the code. Well let’s see how we can do that.

Day 2

How Alexander Proceeded?

Alexander woke up early morning next day. Coffee was in his hand but mind was still thinking about the problem in hand. It was very difficult for him to find the right star from dark sky but finally he managed to find the Moon and there came Approach 2.

Sky – My Brain

Stars – Thoughts

Moon – Solution for Course Library problem

Approach 2 – Simple Factory Approach

In the first approach UI was creating Course Objects.

Now how it will be if the power of object creation is taken away from UI and give it to someone else. Here someone else is called Simple Factory class.

What is Simple Factory?

Simple Factory is a class with a public static method which will actually do the object creation task according to the input it gets.

UI

Advantages of the Approach 2

Whenever new course will be introduced, the one which gets changed is factory not client code.

As Factory is class any one can use it who have access. In short Course logic now can be reused.

Final step – demonstration

Later in the evening Alexander reached Programmer24X7 office to demonstrate this revised architecture. But before Alexander started to express his anxiety, there came another surprising request. Thomas said, “I think, it’s better if we add one more UI for corporate schedule as well. Reason is that, Now-a-days my corporate training count has increased a lot, so it’s becoming impossible for me to manage.”

I) Now the very first thing we should do is, changing course library (because we need to add corporate courses as well).

Problem with the Approach 2

New requirements are easily covered using Simple Factory Approach, then what’s the matter?

All though all classes are derived from Abstract Course, adding five case conditions in a single Simple Factory violates SOLID Principle SRP – Single Responsibility Principle. (SRP says a class should have only one reason to change.)
And here Factory class will be changed

Whenever new corporate course introduces or modified.

Whenever new online course introduces or modified.

So this Simple Factory solution will not workout in current problem context.

Day 4

Next day Alexander reached Programmer24X7 and explained the architecture to Thomas What is Thomas’s reply? Good or Bad?

Small transcript of the big discussion we had after looking into the architecture.

Thomas: Sorry Alexander but I don’t think this solution will work.

Alexander: Why Sir?

Thomas: See, it’s great that there exist a separate Factory for every Course group. (OnlineCourseFactory, CoporateCourseFactory).
But how will you keep a control over each and every factory. I meant how you will make sure that every factory is creating objects properly, for instance how will you be sure that each factory is following a company standard and creates course materials and schedule prior to returning the object.
It may possible that in future one more kind of factory say OfflineCourseFactory is added for managing offline courses and unknowingly it just violates the company standard and creates course materials in his own way.

Alexander: You are right Sir. Let me think about a full proof and final solution, Give me a day.

Thomas: No problem Alexander. Have a nice day.

Problem with the Approach 3

Every factory is independent here. There is no strict rule for defining factories. In this approach each factory can have their own structure and standards.

Day 5

What Alexander was talking about last night?

Put all common functionalities in a single place (class) and reuse them in all factories.
We call it “ReusbaleClass” for discussion purpose. We need reusability –
we can do it by 2 ways.

With inheritance – Derive all Factories from ReusbaleClass –> Call it Solution 1

With composition – All factories will have a member of type ReusbaleClass –> Call it Solution 2

Let factories override some functionality (which is different for every factory) defined in ReusbaleClass.

We need to override means Solution 1 will fit perfect.

Approach 4 – Factory Method Approach

In short we need a class here which will do all the common tasks and expose a virtual or abstract function.

So let’s create AbstractCourseFactory which will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our OnlineCourseFactory and CorporateCourseFactory.

Advantages with the Approach 4

If in the future a new course group (say for instance offline course) introduced in Programmer24X7, a new factory will be derived from AbstractCourse, encapsulating creation of all concrete courses (say for instance Offline Java Courses, Offline .NET Course) related to that group. It’s that simple.

That’s all about the Factory Method patterns. Finally Thomas seems happy because all his requirements seem satisfied and Alexander is also happy because now he has become champ in Factory Method Pattern.

Additional approaches and thoughts

Is parent factory has to be abstract always?
Answer for this question is No. We can make it non abstract if required and add default implementation to GetCourse method making it virtual.

Is switch is must in factories?
No. We can replace switch loop with the Dictionary in .NET.

Is inheritance from second level factory is possible?
Yes absolutely and that’s how factory method works. Initially we had AbstractCourseFactory with its default implementation for GetCourse method, which will be later extended by OnlineCourseFactory adding its own implementation for GetCourse method, which in turn can be a virtual method. So that later say when a new OnlineAdvanceCourse is introduced in Programmer24X7 existing, OnlineCourseFactory can easily be extended.

What will be the advantage of using MultiLevel inheritance in case of Factory Method Pattern?
Well, consider following scenario.

We have our AbstractCourseFactory and OnlineCourseFactory.

OnlineCourseFactory override GetCourse method for defining online courses that is Java and .net.

Now let’s assume new courses are added after some year to Online Course and we are not even interested in opening OnlineCourseFactory.

OnlineCourseFactoryVersion2 will be introduced now.

Now if we derive OnlineAdvanceCourseFactory from AbstractCourseFactory we are supposed to define all previous courses like Java and .NET along with new one resulting redundant code.

Other than that what we can do is we will take help of Dictionaries for storing all available courses, and goes adding courses to it on each level.