mardi 14 février 2017

A lock that decides which function may be called

I have 3 classes: A, B and C where both B and C inherit from A. Both B and C need to implement a method called prepare which may be called x times and once the preparation stage is done, the function final_calculation may be called. I was thinking of making both classes have a boolean which toggles, depending on whether or not we are in the preparation stage. If we are in the preparation stage, only the prepare function can be called, else only the final_calculation function. So A would look something like this:

class A:

def __init__(self):
    self.prepare_state = True

def toggle_state(self):
    self.prepare_state = not self.prepare_state

def prepare(self):
    if self.prepare_state is False:
        raise StateError

def final_calculation(self):
    if self.prepare_state is True:
        raise StateError

Does this make sense? It reminds me a bit of a Singleton or the State pattern and it reminds me of a mutex which I haven't really worked with before. Is there a design pattern for what I'm trying to do? I don't want to re-invent the wheel, so any keywords as to what I should search for are welcome.

Aucun commentaire:

Enregistrer un commentaire