More than 500,000 copies of “Design Patterns: Elements of Reusable Object-Oriented Software” have been sold since its release in 1994. The book for software de­vel­op­ers describes 23 different design patterns, also known in pro­fes­sion­al circles as “Gang of Four” design patterns – a term that goes back to the four authors Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm.

Among the many design strate­gies taught in this pub­li­ca­tion is the so-called factory method, which allows a class to delegate the creation of objects to sub­class­es. Concrete in­for­ma­tion on how to use this practical method is provided in par­tic­u­lar by the factory method pattern, which is often today simply referred to as the factory pattern.

What is the factory pattern (factory method pattern)?

Note

The SOLID prin­ci­ples are a subset of the prin­ci­ples of object-oriented design, which are intended to improve the de­vel­op­ment process of object-oriented software. The acronym ‘SOLID’ stands for the following five prin­ci­ples:

- Single re­spon­si­bil­i­ty principle: Each class should have only one re­spon­si­bil­i­ty.

- Open-closed-principle: Software units should be ex­pand­able without having to change their behaviour.

- Liskov sub­sti­tu­tion principle: A derived class should always be used instead of its base class.

- Interface seg­re­ga­tion principle: In­ter­faces should be perfectly adapted to the re­quire­ments of the accessing clients.

- Dependency inversion principle: Classes on a higher level of ab­strac­tion should never depend on classes on a lower level of ab­strac­tion.

Instead of the usual de­scrip­tion, the ab­bre­vi­at­ed term ‘factory pattern’ or ‘factory method design pattern’ is used in many cases, although it’s nowhere to be found in the GoF. If you look into the book, you’ll find that – besides the factory method pattern discussed here – only the similar abstract factory pattern exists, which defines an interface for the creation of a family of objects whose concrete classes are only defined during runtime.

What is the goal of the factory method pattern?

The factory pattern aims to solve a fun­da­men­tal problem in in­stan­ti­a­tion – i.e., the creation of a concrete object of a class – in object-oriented pro­gram­ming. In principle, creating an object directly within the class that needs or should use this object is possible, but very in­flex­i­ble. It binds the class to this object and makes it im­pos­si­ble to change the in­stan­ti­a­tion in­de­pen­dent­ly of the class. This kind of code is avoided in the factory pattern approach by first defining a separate operation for creating the object – the factory method. As soon as this is called up, it generates the object instead of the class con­struc­tor already mentioned.

Factory pattern: UML diagram of the factory method pattern

In software that is based on the factory method design pattern, the code of an object to be created (in this context also referred to as the “product”) is out­sourced into a separate class. This abstract class, also called the “creator” or – matching the pattern – “factory”, delegates the object in­stan­ti­a­tion to a subclass (Con­crete­Cre­ator), which ul­ti­mate­ly decides which product is created. For this purpose, the Con­crete­Cre­ator takes over the method cre­ateProd­uct() and returns a Con­creteProd­uct, which can op­tion­al­ly be extended by the Creator with pro­duc­tion code before it is passed to the interface as a finished product.

The process is made clear in the below UML class diagram of the factory pattern, which graph­i­cal­ly sum­ma­rizes the re­la­tion­ships and processes described.

The pros and cons of the factory method design pattern

In the factory pattern, calling a pro­gram­ming method is com­plete­ly separated from the im­ple­men­ta­tion of new classes, which comes with its ad­van­tages. For example, this condition has a par­tic­u­lar effect on how software can be extended: Factory methods have a high degree of autonomy which means they let you add new classes without the ap­pli­ca­tion having to change in any way – in parallel to runtime. In doing so, it’s suf­fi­cient to implement the factory interface and in­cor­po­rate the creator ac­cord­ing­ly (via Con­crete­Cre­ator).

Another advantage is the straight­for­ward testa­bil­i­ty of the factory com­po­nents. For example, if a Creator im­ple­ments three classes, their func­tion­al­i­ty can be tested in­di­vid­u­al­ly and in­de­pen­dent­ly of the class that’s being called out. In the case of the latter, it is only necessary to ensure that it calls out the creator properly, even if the software is extended at a later point in time. A further advantage is the pos­si­bil­i­ty to give factory methods (unlike a class con­struc­tor) a mean­ing­ful name.

The biggest weakness of the factory design pattern is the fact that its im­ple­men­ta­tion leads to a strong increase in the number of in­te­grat­ed classes, because every Con­creteProd­uct always requires a Con­crete­Cre­ator. As prof­itable as the factory approach is in principle regarding the extension of software, it is also dis­ad­van­ta­geous when it comes to the effort required: If a product family is to be extended, not only the interface but all sub­or­di­nate Con­crete­Cre­ator classes have to be adapted ac­cord­ing­ly. Solid planning in advance regarding the required product types is therefore in­dis­pens­able.

Ad­van­tages Dis­ad­van­tages
Modular ex­pand­abil­i­ty of the ap­pli­ca­tion High number of required classes
Good testa­bil­i­ty Extension of the ap­pli­ca­tion is very elaborate
Sig­nif­i­cant method names

Where is the factory method pattern used?

The factory pattern can prove valuable in various ap­pli­ca­tion scenarios. Software where the concrete products to be created are unknown or are not defined in advance benefits from the al­ter­na­tive approach for subclass man­age­ment. Typical use cases include frame­works or class libraries, which have become virtually in­dis­pens­able as a basic framework for the de­vel­op­ment of modern ap­pli­ca­tions.

Au­then­ti­ca­tion systems also benefit from the ad­van­tages of the factory design pattern: Instead of a central class with various pa­ra­me­ters that vary according to user au­tho­riza­tion, the au­then­ti­ca­tion process can be delegated to factory classes that make in­de­pen­dent decisions about the handling of the re­spec­tive user.

In addition, the design according to the factory pattern approach is generally suitable for all software in which new classes are added regularly and according to plan – es­pe­cial­ly if these classes have to go through the same creation process.

Factory pattern: example (PHP)

The factory method design pattern can be used in various ap­pli­ca­tions in different pro­gram­ming languages. Some of the best-known rep­re­sen­ta­tives include Java, JavaScript, C++, C#, Python, and PHP. The latter scripting language is also used in the following practical example, which is inspired by a German blog post by Ph­p­mon­keys.

In this case, a scenario with the abstract class “Car” (Creator) and the factory class “Car­Fac­to­ry” (Con­crete­Cre­ator) is set. The former is designed as simple as possible and contains only code to set a color for the car – default color: white – and to read it out:

class Car {
	private $color = null;
	public function __construct() {
		$this->color = "white";
	}
	public function setColor($color) {
		$this->color = $color;
	}
	public function getColor() {
		return $this->color;
	}
}

In the factory class, methods for “red” and “blue” cars and a private method for the actual class creation are in­tro­duced:

class CarFactory {
	private function __construct() {
	}
	public static function getBlueCar() {
		return self::getCar("blue");
	}
	public static function getRedCar() {
		return self::getCar("red");
	}
	private static function getCar($color) {
		$car = new Car();
		$car->setColor($color);
		return $car;
	}
}

Thanks to the factory method pattern, this clearly arranged factory method can now be extended with a wide variety of ad­di­tion­al features such as ad­di­tion­al colors, the brand of the car, or its price.

Go to Main Menu