I have a data processor class in Python/pseudocode that iterates through a large array, does some calculation and then saves the result into a file chunk by chunk. This scenario is depicted by the following snippet. Although it does the expected task, the file handling is not part of the logic, and hence, it should be eliminated.
class DataProcessor:
def do_some_operation(self):
init_file('some/path/to/file') # Not part of logic
for data in large_data:
result = calculation(data)
write_to_file(result) # Not part of logic
close_file() # Not part of logic
I have thought of introducing the Observer design pattern as the following:
class DataProcessorObserver:
def update(self, some_data):
...
class FileObserver(DataProcessorObserver):
def __init__(self):
init_file('some/path/to/file')
def __del__(self):
close_file()
def update(self, some_data):
write_to_file(some_data)
class NewDataProcessor:
def __init__(self):
self.dp_observers = []
def notify_observers(some_data):
for observer in self.dp_observers:
observer.update(some_data)
def do_some_operation(self):
for data in large_data:
result = calculation(data)
self.notify_observers(result)
My question is whether the above approach is a good one, or what other solutions exist to resolve this issue?
Thank you.
Aucun commentaire:
Enregistrer un commentaire