sideara-image

Lorem ipsum dolor sit . Proin gravida nibh vel vealiquete sollicitudin, lorem quis bibendum auctonisilin sequat. Nam nec tellus a odio tincidunt auctor ornare.

Stay Connected & Follow us

What are you looking for?

Simply enter your keyword and we will help you find what you need.

Blog

Fun with Factory Design Pattern and Python

What is the design pattern/ Software design pattern?

When pattern word comes to us what do we think?

When software engineers try to solve a problem, always try to find a pattern that they already used before or try to create a new one. Because it is very important for future uses and others can understand it well. That’s why design pattern comes and there are some patterns that are approved worldwide. These are very much logical things. Not dependent on any programming language.

In software engineering, a design pattern is a known repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. (Collected from Source Making)

What is a Factory Design Pattern?

When I use the factory word you may have made a picture of a factory right?

Don’t worry, you are right.

Think about a factory where they produce cars. You don’t know how they do it. But you can order a car from there and you can ride it. This is actually a factory pattern says.

Let’s read about the definition.

The factory design pattern is a design pattern under the creational pattern, which is not exposing the creational logic to the users. This is one of the most used creational patterns by software engineers.

Now let’s make some fun with the factory design pattern.

I think the above bike factory image is enough to understand the whole logic of the factory design pattern.

Specialties of this pattern

  • Separate creation from uses
  • Does not expose the creational logic to users
  • Makes code more robust, less coupled, and easy to implement
  • You can extend without touching the original code.
  • Almost many object creational problems can be solved by this pattern

Now let’s try to draw a UML diagram for the factory pattern.

Now it’s time to implement this pattern using Python code.

Let’s create an Abstract bike class.

from abc import ABC, abstractmethod


class AbstarctBike:
    color = ""

    def create_chassis(self):
        print("Create bike chassis")

    def create_engine(self):
        print("Create bike engine")

    @abstractmethod
    def coloring(self):
        print("Coloring the bike")

Now creates all specific bikes with color and inherit the abstract class.

class YellowBike(AbstarctBike):
    color = "yellow"

    def coloring(self):
        return f"Coloring the bike {self.color}"


class BlueBike(AbstarctBike):
    color = "blue"

    def coloring(self):
        return f"Coloring the bike {self.color}"

 
class RedBike(AbstarctBike):
    color = "red"

    def coloring(self):
        return f"Coloring the bike {self.color}"

If the user wants any other color or make mistake with color spelling we can add another custom exception to message him.

class ColorNotMatch(Exception):
    pass

Now create the Factory

class BikeFactory:
    def create_bike(self, color):
        if color == "yellow":
            return YellowBike()
        if color == "red":
            return RedBike()
        if color == "blue":
            return BlueBike()
        raise ColorNotMatch("Your requested color not match!")

This is an easily readable version of the factory class where we have created too many conditions. Let’s short it.

class BikeFactory:
    def create_bike(self, color):
      targetclass = color.capitalize()
      try:
         return globals()[f"{targetclass}Bike"]()
      except KeyError:
         raise ColorNotMatch("This color is not available!")

Now creates different bikes.

if __name__ == "__main__":
    bike_obj = BikeFactory()
    red_bike = bike_obj.create_bike("red")
    print(red_bike.color)
    print(red_bike.coloring())

The output will be

red
Coloring the bike red

Hope you enjoyed it well. Thanks for reading.

author avatar
Md. Raisul Islam
No Comments

Sorry, the comment form is closed at this time.