Wednesday, January 1, 2014

Factory Pattern

Factory pattern is a creational design pattern. It allows creation of objects without exposing internal logic to client. It allows subclasses to decide which class to instantiate. 

Let's look at how we can implement factory pattern.


This is one of the simplest ways to implement factory pattern (noob implementation). Problem is once we add a new employee type we should modify the factory method which violates open/closed principle. We can subclass factory class but factory classes are often used as singleton.

Here's a practical example on database connection.

Using Reflection

We can use reflection to avoid modification to factory class

But reflection comes with the cost of performance. You can use class registration mechanism without using reflection even.

Factory pattern In JavaScript

Factory in JavaScript : method1 (addyosmani) and method2 (carldanley)

When to use Factory

Before implementing factory method in your code think if it is really necessary to implement one because it might add unnecessary complexity to your code.

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook