装饰器模式和适配器模式如何实现?
中等
答题要点
# 装饰器模式(不是Python装饰器语法)
from abc import ABC, abstractmethod
class DataSource(ABC):
@abstractmethod
def read(self) -> str:
pass
class FileDataSource(DataSource):
def __init__(self, path: str):
self.path = path
def read(self) -> str:
with open(self.path) as f:
return f.read()
class DataSourceDecorator(DataSource):
def __init__(self, source: DataSource):
self._source = source
def read(self) -> str:
return self._source.read()
class EncryptedDataSource(DataSourceDecorator):
def read(self) -> str:
data = super().read()
return self._decrypt(data)
def _decrypt(self, data: str) -> str:
# 解密逻辑
return data
class CachedDataSource(DataSourceDecorator):
def __init__(self, source: DataSource):
super().__init__(source)
self._cache = None
def read(self) -> str:
if self._cache is None:
self._cache = super().read()
return self._cache
# 组合使用
source = CachedDataSource(EncryptedDataSource(FileDataSource('data.txt')))
# 适配器模式
class OldAPI:
def get_data_xml(self):
return "<data><value>100</value></data>"
class NewAPIAdapter:
def __init__(self, old_api: OldAPI):
self._old_api = old_api
def get_data_json(self):
import xml.etree.ElementTree as ET
xml_data = self._old_api.get_data_xml()
root = ET.fromstring(xml_data)
return {'value': root.find('value').text}
# 数据源适配器
class PandasAdapter:
"""将不同数据源适配为DataFrame"""
def __init__(self, source):
self.source = source
def to_dataframe(self):
if hasattr(self.source, 'fetch'):
data = self.source.fetch()
elif hasattr(self.source, 'query'):
data = self.source.query()
else:
raise TypeError("Unsupported source type")
return pd.DataFrame(data)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题