design patterns – Factory Method and Abstract Factory


Help me to understand.

How are these templates different? When is it better to use the former and when is the latter?


Factory method: there is a class that performs its specific function. It delegates part of its functionality to the external interface, which is instantiated through a virtual method of this class. Heirs of this class, overriding this method, can return other implementations of the interface used by the main class algorithm.

Abstract factory: a class / interface that does not contain any logic of its own. All of its methods return instances of other interfaces and are called by external components. This pattern allows, by replacing the implementation of one interface, to replace a set of implementations of a limited set of interfaces.

An abstract factory is used when you need to create a family of interfaces, the implementation of which must be overridden together. For example, when accessing data, there is a standard interface that is responsible for connecting – IDbConnection, and my interface is responsible for converting the request object model into a request text that complies with the standard of a certain DBMS. Both of these interfaces are instantiated by the same factory. At the same time, the IDbConnection interface declares the CreateCommand method, which returns the IDbCommand implementation for the corresponding connection type. This is the factory method.

Scroll to Top