Book Image

Mastering Python Design Patterns

By : Sakis Kasampalis
Book Image

Mastering Python Design Patterns

By: Sakis Kasampalis

Overview of this book

Table of Contents (23 chapters)
Mastering Python Design Patterns
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
The Factory Pattern
Index

Chapter 1. The Factory Pattern

Creational design patterns deal with an object creation [j.mp/wikicrea]. The aim of a creational design pattern is to provide better alternatives for situations where a direct object creation (which in Python happens by the __init__() function [j.mp/divefunc], [Lott14, page 26]) is not convenient.

In the Factory design pattern, a client asks for an object without knowing where the object is coming from (that is, which class is used to generate it). The idea behind a factory is to simplify an object creation. It is easier to track which objects are created if this is done through a central function, in contrast to letting a client create objects using a direct class instantiation [Eckel08, page 187]. A factory reduces the complexity of maintaining an application by decoupling the code that creates an object from the code that uses it [Zlobin13, page 30].

Factories typically come in two forms: the Factory Method, which is a method (or in Pythonic terms, a function) that returns a different object per input parameter [j.mp/factorympat]; the Abstract Factory, which is a group of Factory Methods used to create a family of related products [GOF95, page 100], [j.mp/absfpat].