Many of us are familiar with the use of static factory methods for object creation. However, there is quite a bit of confusion as to whether such static factory methods are the same as the factory pattern. Let me attempt to explain the difference between the two here.
Static factory method
A static factory method also known as named constructor is employed either in place of or in addition to traditional constructors for creating objects of the class.
The advantages of using static factory methods are:
This pattern hides the object creation logic while providing a well defined interface for object creation.
Static factory method
A static factory method also known as named constructor is employed either in place of or in addition to traditional constructors for creating objects of the class.
The advantages of using static factory methods are:
- Meaningful names for constructors
- Choice of creating new object or returning existing one (Ex: used in singletons)
- Can return sub-class objects
Now, static factory method has nothing to do with the Factory pattern. In case of factory pattern, one or more factory methods are defined in a factory class and are used to create objects of multiple possibly unrelated types.
Factory pattern
This pattern hides the object creation logic while providing a well defined interface for object creation.
No comments:
Post a Comment