Python: Start using Factory Pattern design
We all know that the Design patterns are a set of best practices that can be used to solve recurring problems in software development. One of the most popular design patterns is the Factory Pattern
.
In this article, I will show you how Factory Pattern
can simplify object creation and how you can use it to separate creation from use. So lets dive in —
Introducing Factory Method
The Factory Pattern
is a creational design pattern that provides a way to create objects without exposing the creation logic to the client. So this allows you to create objects in a superclass, but allows subclasses to alter the type of objects that will be created
In other words, it provides a way to encapsulate object creation logic and decouple it from the rest of the code.
Basic Implementation of Factory Pattern
Let’s look at an example to see how the Factory Pattern can be implemented in Python.
- Here I have created a simple class hierarchy for different types of animals as shown below:
class Animal:
def speak(self):
pass
class Dog(Animal):
def…