Factory (object-oriented programming)

However, in most languages they are not, and constructors are invoked in a way that is idiomatic to the language, such as by using the keyword new, while a factory has no special status and is invoked via an ordinary method call or function call.

OOP provides polymorphism on object use by method dispatch, formally subtype polymorphism via single dispatch determined by the type of the object on which the method is called.

For example, in Python, the collections.defaultdict class[7] has a constructor which creates an object of type defaultdict[d] whose default values are produced by invoking a factory.

In Python, a factory function f that instantiates a class A can be implemented as: A simple factory function implementing the singleton pattern is: This will create an object when first called, and always return the same object thereafter.

In languages where they differ, one must distinguish them in interfaces, and switching between constructors and factories requires changing the calls.

In languages where objects are dynamically allocated, as in Java or Python, factories are semantically equivalent to constructors.

If a constructor can be passed as an argument to a function, then invocation of the constructor and allocation of the return value must be done dynamically at run time, and thus have similar or identical semantics to invoking a factory.

Factory objects are common in widget toolkits and software frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.

Factory methods are used in test-driven development to allow classes to be put under test.

[9] 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.

In many object-oriented languages, constructors must have the same name as the class they are in, which can lead to ambiguity if there is more than one way to create an object (see overloading).

Factory methods have no such constraint and can have descriptive names; these are sometimes known as alternative constructors.

This can be useful if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.

Each time the program reads an image, it needs to create a reader of the appropriate type based on some information in the file.

Factory Method in LePUS3