Thanks in advance. Given these example of classes...
# registers all that happens during a combat
class CombatLog:
def __init__(self):
self.actions = []
# it handles a combat
class Combat:
def __init__(self):
self.fighters = [] # list of fighter instances
self.combat_log = CombatLog()
def run_round(self):
# do whatever
self.combat_log.log(...)
# are the fighters in a combat
class Fighter:
def __init__(self):
self.property1 = 1
self.property2 = 2
self.attacks = [] # list of attack instances
def attack(self):
# do whatever
self.combat_log.log(...) # clean way to access the log?
class Attack:
def __init__(self):
self.damage = 10
def cast(self):
# do whatever
self.combat_log.log(...) # clean way to access the log?
# from somewhere else in the code
combat1 = Combat()
combat2 = Combat()
I am wondering what would be the best pattern to handle the next requirements:
- There is one unique instance of the CombatLog per Combat. So if there are 2 Combat instances, the combat would have 2 CombatLog instances.
- I want to use the combat log everywhere is needed. For example, if a Fighter, the Combat or Attack, needs to access to the log. The CombatLog is like some "global" object ONLY within that Combat and all the instances within that Combat.
- When the Combat is done and removed from the memory, the CombatLog gets removed as well.
The approaches I am thinking of, but I am not proud/sure of them:
- Pass the log instance through all the children instances (the fighters, and the attacks)
- Make some kind of log manager (like Singleton), and then request the log for that combat from where I want. But i have a similar problem, which is that I have to pass the id of that combat to all chindren in order to request the proper log to the log manager... Which is more o less the same problem than before.
- I was thinking to make some kind of dependency injector, like using decorators or so, but I always crash against the same problem (the one before).
Maybe I need another approach, but I can't think of... The code is in Python.
Thanks a lot for your time.