Reputation: 87
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.
Upvotes: 0
Views: 32
Reputation: 5659
State Design Pattern seems to be an overkill for your use case. It would have made sense if you had more complicated rules for state changes, such as allow final_calculation
only if prepare
of both B
and C
has been called once, or something.
Your current implementation is straightforward and looks good. You can also consider renaming prepare_state
to is_final_calculation_allowed
or is_prepare_done
to make things more clear.
Upvotes: 1