Applicability
The factory pattern can be used when:
- The creation of an object precludes its reuse without significant duplication of code.
- The creation of an object requires access to information or resources that should not be contained within the composing class.
- The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
Factory methods are common in toolkits and frameworks, where library code needs to create objects of types that may be subclassed by applications using the framework.
Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.
Factory methods are used in test-driven development to allow classes to be put under test. If such a class Foo
creates another object Dangerous
that can't be put under automated unit tests (perhaps it communicates with a production database that isn't always available), then the creation of Dangerous
objects is placed in the virtual factory method createDangerous
in class Foo
. For testing, TestFoo
(a subclass of Foo
) is then created, with the virtual factory method createDangerous
overridden to create and return FakeDangerous
, a fake object. Unit tests then use TestFoo
to test the functionality of Foo
without incurring the side effect of using a real Dangerous
object.
Read more about this topic: Factory Method Pattern