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­velopers 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 strategies taught in this pub­lic­a­tion is the so-called factory method, which allows a class to delegate the creation of objects to sub­classes. Concrete in­form­a­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­ciples are a subset of the prin­ciples 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­ciples:

- Single re­spons­ib­il­ity principle: Each class should have only one re­spons­ib­il­ity.

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

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

- Interface se­greg­a­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­ated 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­ment­al problem in in­stan­ti­ation – 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­ible. It binds the class to this object and makes it im­possible to change the in­stan­ti­ation in­de­pend­ently 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­struct­or 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­ation to a subclass (Con­crete­Cre­at­or), which ul­ti­mately decides which product is created. For this purpose, the Con­crete­Cre­at­or takes over the method cre­ate­Product() and returns a Con­crete­Product, which can op­tion­ally 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­ic­ally sum­mar­ises 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­pletely separated from the im­ple­ment­a­tion of new classes, which comes with its ad­vant­ages. 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­plic­a­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­por­ate the creator ac­cord­ingly (via Con­crete­Cre­at­or).

Another advantage is the straight­for­ward test­abil­ity of the factory com­pon­ents. For example, if a Creator im­ple­ments three classes, their func­tion­al­ity can be tested in­di­vidu­ally and in­de­pend­ently 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­sib­il­ity to give factory methods (unlike a class con­struct­or) a mean­ing­ful name.

The biggest weakness of the factory design pattern is the fact that its im­ple­ment­a­tion leads to a strong increase in the number of in­teg­rated classes, because every Con­crete­Product always requires a Con­crete­Cre­at­or. As prof­it­able as the factory approach is in principle regarding the extension of software, it is also dis­ad­vant­age­ous when it comes to the effort required: If a product family is to be extended, not only the interface but all sub­or­din­ate Con­crete­Cre­at­or classes have to be adapted ac­cord­ingly. Solid planning in advance regarding the required product types is therefore in­dis­pens­able.

Ad­vant­ages Dis­ad­vant­ages
Modular ex­pand­ab­il­ity of the ap­plic­a­tion High number of required classes
Good test­abil­ity Extension of the ap­plic­a­tion is very elaborate
Sig­ni­fic­ant method names

Where is the factory method pattern used?

The factory pattern can prove valuable in various ap­plic­a­tion scenarios. Software where the concrete products to be created are unknown or are not defined in advance benefits from the al­tern­at­ive 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­plic­a­tions.

Au­then­tic­a­tion systems also benefit from the ad­vant­ages of the factory design pattern: Instead of a central class with various para­met­ers that vary according to user au­thor­isa­tion, the au­then­tic­a­tion process can be delegated to factory classes that make in­de­pend­ent decisions about the handling of the re­spect­ive 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­cially 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­plic­a­tions in different pro­gram­ming languages. Some of the best-known rep­res­ent­at­ives include Java, JavaS­cript, 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 Php­mon­keys.

In this case, a scenario with the abstract class ‘Car’ (Creator) and the factory class ‘Car­Fact­ory’ (Con­crete­Cre­at­or) is set. The former is designed as simple as possible and contains only code to set a colour for the car – default colour: 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 colours, the brand of the car, or its price.

Go to Main Menu