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.
Here's a practical example on database connection.
Using Reflection
We can use reflection to avoid modification to factory class
see example on http://www.oodesign.com/factory-pattern.html
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