I am designing a parking lot. Now I have three kinds of parking spots. I want to initialize my parking lot like this:
Building({Size.SMALL: 5, Size.MEDIUM: 6, Size.LARGE: 7})
This means this parking lot has
- 5 small spots,
- 6 medium spots and
- 7 large spots.
And below is my code for spots and the parking lot (i.e., Building).
from enum import Enum
class Size(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
class Spot:
def __init__(self, id) -> None:
self.id = id
self.vehicle = None
class SmallSpot(Spot):
def __init__(self, id) -> None:
super().__init__(id)
class MediumSpot(Spot):
def __init__(self, id) -> None:
super().__init__(id)
class LargeSpot(Spot):
def __init__(self, id) -> None:
super().__init__(id)
class Building:
def __init__(self, dic: dict[Size, int]) -> None:
for size, count in list(dic.items()):
if size == Size.SMALL:
self.small_spot_list = [SmallSpot(i) for i in range(count)]
elif size == Size.MEDIUM:
self.medium_spot_list = [MediumSpot(i) for i in range(count)]
elif size == Size.LARGE:
self.large_spot_list = [LargeSpot(i) for i in range(count)]
My question is, how can I rewrite the __init__()
function of Building so that I don't need to explicitly write these enums in the code so that if there are new kinds of spots added, I will not need to modify the code in this function (such as add more if-else statements for new vehicle types)?
I believe it's called Open-Closed Principle.