Factory pattern
Фабрика
A way to move object creation out of the code that uses the object. The caller gets something it can work with without having to pick a concrete class or know how to set it up.
Also known as: фабричный метод, factory method
What a factory does
Imagine a reporting tool that exports CSV and JSON. The export workflow is the same either way: load the rows, render them, and write the result. What changes is the renderer. Rather than putting format checks and constructor calls throughout the workflow, you can give that workflow a factory and let it deal only with the renderer's shared interface.
A factory isn't always Factory Method
In everyday code reviews, a factory might be a function such as make_renderer(format) that looks up or selects an implementation. That's often called a simple factory. A switch or lookup table is fine when the format comes from configuration and the set of formats is small.
Factory Method, the Gang of Four design pattern, uses an overridable method as the creation hook. A base class defines a workflow that calls the hook. A subclass decides which concrete object to return, while the inherited workflow continues to use the same interface.
Example in Python
Assume CsvRenderer and JsonRenderer both provide render(rows). The base class handles writing the output; a subclass supplies the renderer:
from abc import ABC, abstractmethod
class ExportJob(ABC):
@abstractmethod
def make_renderer(self):
pass
def run(self, rows, output):
output.write(self.make_renderer().render(rows))
class CsvExportJob(ExportJob):
def make_renderer(self):
return CsvRenderer()
A JsonExportJob can override make_renderer() to return a JsonRenderer without changing run(). Something still has to choose which job to run, such as the code that reads the command-line options. The pattern moves that choice out of the export workflow; it doesn't eliminate it.
When to use it
Use a factory when choosing or configuring an implementation would otherwise leak into the code that uses it. A direct constructor is clearer if there is only one implementation and setup is trivial. If the workflow merely needs an object that's already available, pass that object in rather than adding a creation hook. Use Factory Method when subclasses already represent useful variations of a shared workflow, not just to avoid a constructor call.
In an interview
Ask which meaning of “factory” the interviewer has in mind. A static method named create can be a factory in the everyday sense, but its name alone doesn't make it the GoF pattern. If asked about Abstract Factory, focus on what it creates: a family of compatible objects, such as buttons and menus for the same UI theme.