I’m trying to understand the concept of the Delegation programming technique.
Composition:
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine() # Composition: Car has an Engine
def drive(self):
return self.engine.start()
# Usage
car = Car()
print(car.drive()) # Output: Engine started
Dependency Injection:
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self, engine):
self.engine = engine # Dependency Injection
def drive(self):
return self.engine.start()
# Usage
car = Car(Engine())
print(car.drive()) # Output: Engine started
Most websites I’ve searched, when trying to explain delegation, either use something equal to composition, or something equal to dependency injection…
Any help would be appreciated.
New contributor
An old man in the sea. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.