In the following example code, I want every car
object to be composed of brake_system
and engine_system
objects, which are stored as attributes on the car.
To implement this, I've defined Car
, BreakSystem
and EngineSystem
as abstract classes. Every subclass of Car
is required to define its respective BreakSystem
and EngineSystem
subclasses as class attributes.
Are there any potential problems with this approach? Or are there other design patterns better suited to handle nested abstractions?
from abc import ABC, abstractmethod
class Car(ABC):
"""
every car object should have an Engine object and a BrakeSystem object
"""
def __init__(self):
self.engine_system = self._engine_type()
self.brake_system = self._brake_type()
@property
@abstractmethod
def _engine_type(self):
raise NotImplementedError()
@property
@abstractmethod
def _brake_type(self):
raise NotImplementedError()
class EngineSystem(ABC):
pass
class BrakeSystem(ABC):
pass
class FooBrakeSystem(BrakeSystem):
pass
class FooEngineSystem(EngineSystem):
pass
class FooCar(Car):
_engine_type = FooEngineSystem
_brake_type = FooBrakeSystem
if __name__ == '__main__':
obj = FooCar()
Aucun commentaire:
Enregistrer un commentaire