diff --git a/examples/providers/factory_aggregate/example.py b/examples/providers/factory_aggregate/example.py new file mode 100644 index 00000000..d76d8392 --- /dev/null +++ b/examples/providers/factory_aggregate/example.py @@ -0,0 +1,27 @@ +"""`FactoryAggregate` providers example.""" + +import sys + +from dependency_injector.providers import Factory + +from prototype import FactoryAggregate +from games import Chess, Checkers, Ludo + + +game_factory = FactoryAggregate(chess=Factory(Chess), + checkers=Factory(Checkers), + ludo=Factory(Ludo)) + +if __name__ == '__main__': + game_type = sys.argv[1].lower() + selected_game = game_factory.create(game_type) + selected_game.play() + + # $ python example.py chess + # Playing chess + + # $ python example.py checkers + # Playing checkers + + # $ python example.py ludo + # Playing ludo diff --git a/examples/providers/factory_aggregate/games.py b/examples/providers/factory_aggregate/games.py new file mode 100644 index 00000000..c9662b74 --- /dev/null +++ b/examples/providers/factory_aggregate/games.py @@ -0,0 +1,21 @@ +"""Example module.""" + + +class Game(object): + """Base game class.""" + + def play(self): + """Play game.""" + print('Playing {0}'.format(self.__class__.__name__.lower())) + + +class Chess(Game): + """Chess game.""" + + +class Checkers(Game): + """Checkers game.""" + + +class Ludo(Game): + """Ludo game.""" diff --git a/examples/providers/factory_aggregate/prototype.py b/examples/providers/factory_aggregate/prototype.py new file mode 100644 index 00000000..2de72c3c --- /dev/null +++ b/examples/providers/factory_aggregate/prototype.py @@ -0,0 +1,24 @@ +"""FactoryAggregate provider prototype.""" + + +class FactoryAggregate(object): + """FactoryAggregate provider prototype.""" + + def __init__(self, **factories): + """Initializer.""" + self._factories = factories + + def __getattr__(self, factory_name): + """Return factory.""" + if factory_name not in self._factories: + raise AttributeError('There is no such factory') + return self._factories[factory_name] + + def create(self, factory_name, *args, **kwargs): + """Create object.""" + if factory_name not in self._factories: + raise AttributeError('There is no such factory') + + factory = self._factories[factory_name] + + return factory(*args, **kwargs)