| Total Complexity | 5 |
| Total Lines | 37 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | """This module is responsible to define an interface to construct Command objects (instances of the Command class).""" |
||
| 2 | from abc import ABC, abstractmethod |
||
| 3 | from .command_interface import CommandInterface |
||
| 4 | |||
| 5 | |||
| 6 | class CommandFactoryInterface(ABC): |
||
| 7 | """Define a way to create objects of type Command. |
||
| 8 | |||
| 9 | Classes implementing this interface define a way to construct (initialize) new Command objects (class instances). |
||
| 10 | """ |
||
| 11 | @abstractmethod |
||
| 12 | def construct(self, *args, **kwargs) -> CommandInterface: |
||
| 13 | """Construct a new Command object (new class instance) that can be executed. |
||
| 14 | |||
| 15 | Returns: |
||
| 16 | Command: the command object (instance) |
||
| 17 | """ |
||
| 18 | raise NotImplementedError |
||
| 19 | |||
| 20 | |||
| 21 | class CommandFactoryType(type): |
||
| 22 | def __new__(mcs, *args, **kwargs): |
||
| 23 | command_factory_type = super().__new__(mcs, *args, **kwargs) |
||
| 24 | command_factory_type.subclasses = {} |
||
| 25 | return command_factory_type |
||
| 26 | |||
| 27 | def register_as_subclass(cls, factory_type): |
||
| 28 | def wrapper(subclass): |
||
| 29 | cls.subclasses[factory_type] = subclass |
||
| 30 | return subclass |
||
| 31 | return wrapper |
||
| 32 | |||
| 33 | def create(cls, factory_type, *args, **kwargs): |
||
| 34 | if factory_type not in cls.subclasses: |
||
| 35 | raise ValueError('Bad "Factory type" \'{}\''.format(factory_type)) |
||
| 36 | return cls.subclasses[factory_type](*args, **kwargs) |
||
| 37 |