Add example & prototype of factory aggregate

This commit is contained in:
Roman Mogylatov 2017-10-04 00:01:49 +03:00
parent be42d247d8
commit a548924969
3 changed files with 72 additions and 0 deletions

View File

@ -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

View File

@ -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."""

View File

@ -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)