The Factory Method is also known as a Class factory and factory function. Each of these create instances of a class or structure. There are two broad categories of class factories:
Both categories can also be set up to support the Singleton Pattern, just by caching the first instance of whatever is being created and the returning the cached instance on subsequent calls to the factory.
A class factory can be a function or a method on a class. In the case of a method on a class, first instantiate the class then call a method on the instantiation to create an instance of another class or structure. There are many variations on a theme with class factories.
Class factories are typically used to instantiate a class but return the instance represented by an interface. In this way, the details of how the core class is created is hidden away and the rest of the program only has an interface to work with, thus creating good de-coupling and encapsulation of functionality.
Here is a simple example of a class factory function in C++ that returns a new instance of a class every time it is called:
Note that arguments for the class to use can be passed to the class factory function; these are passed on to the class constructor. The rest of the program has no idea how the IMyInterface is implemented and no access to the internals of the MyClass class. An instance of the IMyInterface is available only through the class factory.
A class function that can return instances of more than one class is basically a variation on the same class function shown above. However, all the classes must implement the same interface. An argument is passed to the class factory function to specify which class to instantiate.
See the Singleton Pattern page for class factories that provide a singleton instance of one class.
The following links into the implementation of some of the other design patterns provide further examples of the factory pattern in use:
C
C++
C#
Python