I've read both visitor&strategy patterns are a good choice when it comes to export data into multiple file formats. I'd like to understand how to apply both so I've created a really simple dummy snippet :
class SubWidget:
def __init__(self, parent):
self.parent = parent
class SubWidget1(SubWidget):
def __init__(self, parent, a):
super().__init__(parent)
self.a = a
def restore_state(self, state):
self.a = state["a"]
def save_state(self):
return {"a": self.a}
class SubWidget2(SubWidget):
def __init__(self, parent, a, b):
super().__init__(parent)
self.a = a
self.b = b
def restore_state(self, state):
self.a = state["a"]
self.b = state["b"]
def save_state(self):
return {"a": self.a, "b": self.b}
class Element:
def __init__(self, a, b):
self.a = a
self.b = b
@classmethod
def from_state(cls, state):
return cls(state["a"], state["b"])
def save_state(self):
return {"a": self.a, "b": self.b}
class Widget:
def __init__(self):
self.subwidgets = {
"subwidget1": SubWidget1(self, 1),
"subwidget2": SubWidget2(self, 2, 3),
}
self.elements = [Element(4, 5)]
def save_state(self):
return {
"subwidgets": {k: v.save_state() for k, v in self.subwidgets.items()},
"elements": [v.save_state() for v in self.elements],
}
def restore_state(self, state):
for k, substate in state["subwidgets"].items():
self.subwidgets[k].restore_state(substate)
self.elements = [Element.from_state(substate) for substate in state["elements"]]
if __name__ == "__main__":
w = Widget()
st = w.save_state()
w2 = Widget()
w2.restore_state(st)
Let's assume both the number of subwidgets classes as their internal represantion may grow up and change over time. Let's also say that'd be desirable to be able to export the Elements object in different file formats.
Which design patterns would you use on this particular simple example? How can you grant your design will
support different file versions over time with no sweat? Is it an antipattern having
save_state/restore_state
methods or from_state
static class method per class?
I wanted the question to be language agnostic but I thought by providing a simple dummy python code could enrich the question content a bit. In any case, in the real world case we'd be talking about a complex widget that will have some dynamically loaded (plugins) subwidgets... as analogy think of tools such as photoshop, 3dsmax, ... on these tools you'll see multiple subtools (SubWidget) and internal model/data (elements). I know the code is an oversimplification but the goal is to know which are the right design patterns to apply on this typical case and how to apply them.