Certainly! The Factory Pattern is a creational design pattern that allows you to create objects without specifying the exact class of object that will be created. In your case, you want a Transformation service where different file types (e.g., CSV, JSON, XML) have their own transformation subclasses, and a factory produces the correct transformer based on the file type.
Here's a Python example implementing such a pattern:
from abc import ABC, abstractmethod
# Abstract base class for all transformation services
class TransformationService(ABC):
def __init__(self, data):
self.data = data
@abstractmethod
def transform(self):
pass
# Concrete transformation for CSV files
class CSVTransformation(TransformationService):
def transform(self):
# Example transformation: split data by line and commas
lines = self.data.strip().split('\n')
transformed = [line.split(',') for line in lines]
print(f"CSV transformed data: {transformed}")
return transformed
# Concrete transformation for JSON files
import json
class JSONTransformation(TransformationService):
def transform(self):
# Example transformation: parse JSON string into dict
transformed = json.loads(self.data)
print(f"JSON transformed data: {transformed}")
return transformed
# Concrete transformation for XML files
import xml.etree.ElementTree as ET
class XMLTransformation(TransformationService):
def transform(self):
# Example transformation: parse XML string into an ElementTree Element
root = ET.fromstring(self.data)
transformed = {child.tag: child.text for child in root}
print(f"XML transformed data: {transformed}")
return transformed
# Factory class
class TransformationFactory:
@staticmethod
def get_transformation_service(file_type: str, data: str) -> TransformationService:
if file_type == 'csv':
return CSVTransformation(data)
elif file_type == 'json':
return JSONTransformation(data)
elif file_type == 'xml':
return XMLTransformation(data)
else:
raise ValueError(f"Unknown file type: {file_type}")
# Usage example:
if __name__ == "__main__":
csv_data = "name,age\nAlice,30\nBob,25"
json_data = '{"name": "Alice", "age": 30}'
xml_data = "<person><name>Alice</name><age>30</age></person>"
for file_type, data in [('csv', csv_data), ('json', json_data), ('xml', xml_data)]:
service = TransformationFactory.get_transformation_service(file_type, data)
result = service.transform()
Explanation:
TransformationService is the abstract base class with an abstract method transform().
CSVTransformation, JSONTransformation, and XMLTransformation are concrete subclasses implementing the transform() method for different file types.
TransformationFactory is a simple factory class that, based on the file type string, returns an instance of the correct transformation subclass.
- The client code uses the factory to get the correct transformer and calls the
transform() method without worrying about the specific class.
Would you like a more advanced example with registration or handling more file types?