One thing I did before is to create a common class that each concrete implementation inherits from. Then there is a specification that can be easily followed, and each implementation can avoid repeating certain code that they will all use.
This is a bad example, but you can see how you could force the splash object to use any of the specified classes, and the rest of your code would not care.
class SaverTemplate(object): def __init__(self, name, obj): self.name = name self.obj = obj def save(self): raise NotImplementedError import json class JsonSaver(SaverTemplate): def save(self): file = open(self.name + '.json', 'wb') json.dump(self.object, file) file.close() import cPickle class PickleSaver(SaverTemplate): def save(self): file = open(self.name + '.pickle', 'wb') cPickle.dump(self.object, file, protocol=cPickle.HIGHEST_PROTOCOL) file.close() import yaml class PickleSaver(SaverTemplate): def save(self): file = open(self.name + '.yaml', 'wb') yaml.dump(self.object, file) file.close() saver = PickleSaver('whatever', foo) saver.save()
source share