Purpose
- Encapsulates request as an object
- Parameterize various objects
- Supports Queues and Logs
- Undoable Operations and Macros(Sequences of Commands)
Expandable Command Sets
- Create Order
- Update Quantity
- Ship Order
from abc import ABCMeta, abstractmethod, abstractproperty
class ICommand(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class IOrder(metaclass=ABCMeta):
@abstractproperty
def name(self):
pass
@abstractproperty
def description(self):
pass
class CreateOrder(ICommand, IOrder):
name = '--create-order'
description = 'Create Order'
def __init__(self, args):
pass
def execute(self):
print("Created Order\n")
class UpdateOrder(ICommand, IOrder):
name = '--update-quantity'
description = 'Update Quantity <number>'
def __init__(self, args):
self.newqty = args[1]
def execute(self):
oldqty = 5
print("Updated Database")
print(f"Logging: Updated quantity from {oldqty} to {self.newqty}\n")
class ShipOrder(ICommand, IOrder):
name = '--ship-order'
description = 'Ship Order'
def __init__(self, args):
pass
def execute(self):
print("Shipped Order\n")
class NoCommand(ICommand):
def __init__(self, args):
self._command = args[0]
pass
def execute(self):
print(f'No command named {self._command}')
def get_commands():
commands = (CreateOrder, UpdateOrder, ShipOrder)
return dict([cls.name, cls] for cls in commands)
def print_usage(commands):
print('Usage: python amazon --command-name [arguments]')
print('\nCommands:')
for command in commands.values():
print(f'{command.name}: {command.description}')
print('\n')
def parse_commands(commands, args):
command = commands.get(args[0], NoCommand)
return command(args)
def executioner(argv):
if len(argv) < 2:
print_usage(commands)
else:
command = parse_commands(commands, argv[1:])
command.execute()
argv = ['amazon']
argvA = ['amazon', '--create-order']
argvB = ['amazon', '--update-quantity', '3']
argvC = ['amazon', '--ship-order']
argvD = ['amazon', '--delete-order']
commands = get_commands()
executioner(argv)
executioner(argvA)
executioner(argvB)
executioner(argvC)
executioner(argvD)
Usage: python amazon --command-name [arguments] Commands: --create-order: Create Order --update-quantity: Update Quantity <number> --ship-order: Ship Order Created Order Updated Database Logging: Updated quantity from 5 to 3 Shipped Order No command named --delete-order