Author - StudySection Post Views - 118 views
Abstract Factory | Python

Abstract Factory in Python

Introduction

Design patterns are used to make code more scalable and maintainable. There are different categories of design patterns depending upon the problem it solves. Using design patterns it is easy to add new features to existing code without interrupting it.
Creational design pattern solves the problem of instantiating the classes and objects in an efficient way. There are various creational design patterns like a factory, abstract factory, builder, prototype, and singleton methods. In this section, we will discuss the abstract factory method.

Abstract Factory

The Abstract Factory method provides developers with a mechanism to create closely related objects without specifying their concrete class.
Let’s take an example of an online furniture store, there are different types of furniture like sofa, table, chair, almirah, etc. For every newly added furniture in-store, the developer needs to create a class and manually instantiate their objects which is not a good approach for developers.
This problem is solved by automatic object instantiation using abstract factory methods.

Example

In the following example, the furniture_in_store class handles the instantiation of objects of different furniture classes automatically. We will scale the furniture store to any type of furniture without worrying about the existing code.
chart

class Furniture_at_store:
def __init__(self, furniture_factory = None):
self.furniture_factory = furniture_factory
def show_furniture(self):
furniture = self.furniture_factory()
print(f'We have {furniture}')
print(f'its price is {furniture.Price()}')
class Sofa:
def Price(self):
return 25000
def __str__(self):
return "Sofa"
class Chair:
def Price(self):
return 5000
def __str__(self):
return "Chair"
class Table:
def Price(self):
return 10000
def __str__(self):
return 'Table'
if __name__ == "__main__":
item_list = [Sofa,Table,Chair] for item in item_list:
furniture = Furniture_at_store(item)
furniture.show_furniture()

Advantages

  • It is easy to add a new class without making changes to the existing code.
  • Objects created with abstract factory methods are compatible with each other.

Disadvantages

  • Sometimes we end up with lots of small classes.
  • Adding a new class is required to modify the interface.

If you have skills in PHP programming and you want to enhance your career in this field, a PHP Certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri