In computer programming, a factory is an object used for creating other objects. Objects in this case refers to values, functions, or data structures used in code. The factory pattern is a design pattern that relies on factories to make objects rather than creating the objects directly. This allows the code to be easily altered and to maintain flexibility. It is widely used in object-oriented computer programming, which uses objects to build programs and applications.
A factory has a method of each kind of object it can create. A method is essentially a pattern. It consists of a set of instructions, known as a subroutine, that takes in parameters usually provided by the user and outputs a specific object. Most of this occurs behind the scenes without the user or client knowing anything about it.
When using the factory pattern, the program interacts with a common interface rather than directly communicating with classes. A class is used as a template to create objects. Each object of a particular class shares the same behavior and basic attributes. Classes can be further divided into subclasses, each of which inherits some of the attributes of the class to which it belongs. An object of a particular class is known as an instance of that class.
If, for example, the user wanted the program to create a square in a program or operating system that uses the factory pattern, the program would notify the factory that the user needed an object that had four sides of equal length and four right angles. The factory would notify the shape method that a shape was needed. It might pass on some parameters of the square, such as the area the user would like the square to cover.
Subclasses would decide which class should be used. An instance of the class square would be returned to the factory, which would pass it on to the program that first requested it. The user would see only that information was sent to the factory and returned by the factory. The inner workings of the factory cannot be seen.
The advantage of using a factory pattern is that it allows the program to easily be changed. New types can be added to the factory pattern simply by modifying a tiny piece of the client code, usually no more than one line. Other programming patterns require the programmer to alter the code in every location where an object is created.