What known patterns or practices are there for designing "stateful abstract classes"?
Consider the following example: The abstract class Action represents a single logical step that can be performed at a certain point. It depends on other Actions being performed (dependencies) and can the action can result in a successful or errornous state (which should be stored on the Action object as well).
I'm using Python here, but the question is not limited to the Python language, although I am aware that your answer may vary depending on the language you are accustomed to.
class Action:
def __init__(self, name, deps):
self.name = name
self.deps = deps
self.error_message = None # None, str on failure
self.status_code = None # int, 0 on success
self.executed = False
def execute(self):
# Prevent execution if not all dependencies are already executed.
for dep in self.deps:
assert dep.executed
# ... Execute the action, subclass may implement this behaviour
self.executed = True
# ... set error_message and status_code
I can think of a number of ways to implement the abstract Action class, but none appear as a clean solution to me.
-
Add an
Action.execute_impl()method that can be implemented by subclasses, the return value would be assigned tostatus_code, an exception's message could be assigned toerror_message -
Have some other object or method that can execute actions, takes care of checking dependencies and assigning
executed,status_codeanderror_message,Action.execute()would then be purely abstract and implemented by subclasses -
Don't expect
Actionto be subclasses but instead provide anActionImplinterface with anActionImpl.execute(action)method. EveryActionwould then have anActionImpl. (We assume that the implementation ofActionImpl.execute()needs access to theActionobject that it is implemented for)
Aucun commentaire:
Enregistrer un commentaire