Factory pattern is software design pattern which implements concept of the factories. For example compare to other creational patterns this pattern mainly deals with problem of creating new objects without stating exact class of object which will be created. Basic principle of factory pattern is “Define interface to create an object” and let classes that implement interface decide which class object they want to create.
Factory pattern could be used:
- When object creation prevents its reuse without doing duplication of code.
- When creation of object requires access to resources or information which should not be enclosed within composing class.
- To keep consistent behavior of application object generation, management should be centralized which will ensure everybody utilizing the resource from common place and not duplicating same work many times.
Example using classes:
- Define Interface:
- Create first subclass:
- Create second subclass:
- Create factory which will return product(Object) based on demand at runtime:
- Now create client class which will use factory:
- Second example:
Main motivation behind factory pattern was to allow sub classes free to choose what type of the object they want to create. Many other benefits also there when use factory pattern several of which don’t depends on sub classing so that it is common to define “factory methods” which are not polymorphic as to create objects to gain these other benefits. IN this type methods are frequently static.
Factory method should always distinct name because as we know when we define classes then specification says constructors should have same name what class name they are defined this can lead to ambiguity if we have more than one way to create object. Factory methods have no such kind of restriction and we can have full descriptive names. For example if complex numbers created from two real numbers then real numbers could be interpreted as Cartesian or polar coordinates so when using factory methods their meaning is very clear.
- That’s it. Below is list of all design patterns link:
- Chain of Responsibility
- Template Method