Skip to content

Instantly share code, notes, and snippets.

@gennad
Created March 2, 2011 17:42
Show Gist options
  • Save gennad/851348 to your computer and use it in GitHub Desktop.
Save gennad/851348 to your computer and use it in GitHub Desktop.
Command - GoF
class Command:
def execute(self):
raise NotImplementedError()
class Accelerator(Command):
def __init__(self, car):
self.car = car
def execute(self):
self.car.go()
class Brake(Command):
def __init__(self, car):
self.car = car
def execute(self):
self.car.stop()
class Car:
def __init__(self):
self.status = 'stop'
def go(self):
if self.status == 'moving':
print 'The car is moving faster'
else:
print 'The car is moving'
self.status = 'moving'
def stop(self):
if self.status == 'moving':
print 'The car stops'
self.status = 'stop'
else:
print 'Do nothing'
class Driver:
def __init__(self, accelerator, brake):
self.accelerator = accelerator
self.brake = brake
def drive(self):
self.accelerator.execute()
def stop(self):
self.brake.execute()
car = Car()
accelerator = Accelerator(car)
brake = Brake(car)
driver = Driver(accelerator, brake)
driver.drive()
driver.drive()
driver.stop()
driver.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment