mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-22 09:36:48 +03:00
Add example & prototype of factory aggregate
This commit is contained in:
parent
be42d247d8
commit
a548924969
27
examples/providers/factory_aggregate/example.py
Normal file
27
examples/providers/factory_aggregate/example.py
Normal 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
|
21
examples/providers/factory_aggregate/games.py
Normal file
21
examples/providers/factory_aggregate/games.py
Normal 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."""
|
24
examples/providers/factory_aggregate/prototype.py
Normal file
24
examples/providers/factory_aggregate/prototype.py
Normal 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)
|
Loading…
Reference in New Issue
Block a user