【发布时间】:2021-02-21 11:21:18
【问题描述】:
在Architecture Patterns with Python 进行到一半时,我有两个关于如何构建和实例化领域模型类的问题。假设在我的域模型上我有 DepthMap 类:
class DepthMap:
def __init__(self, map: np.ndarray):
self.map = map
根据我从书中的理解,这个类是不正确的,因为它依赖于Numpy,它应该只依赖于 Python 原语,因此问题是:领域模型类是否应该只依赖于 Python 原语,还是有例外?
假设上一个问题的答案是类应该完全依赖于原语,那么从 Numpy 数组创建 DepthMap 的正确方法是什么?假设现在我有更多格式可以制作 DepthMap 对象。
class DepthMap:
def __init__(self, map: List):
self.map = map
@classmethod
def from_numpy(cls, map: np.ndarray):
return cls(map.tolist())
@classmethod
def from_str(cls, map: str):
return cls([float(i) for i in s.split(',')])
或工厂:
class DepthMapFactory:
@staticmethod
def from_numpy(map: np.ndarray):
return DepthMap(map.tolist())
@staticmethod
def from_str(map: str):
return DepthMap([float(i) for i in s.split(',')])
我认为即使是他们在书中提到的Repository Pattern,也可以放在这里:
class StrRepository:
def get(map: str):
return DepthMap([float(i) for i in s.split(',')])
class NumpyRepository:
def get(map: np.ndarray):
return DepthMap(map.tolist())
第二个问题:从不同来源创建领域模型对象时,正确的做法是什么?
注意:我的背景不是软件;因此某些 OOP 概念可能不正确。不要投反对票,请发表评论并让我知道如何改进问题。
【问题讨论】:
标签: python oop architecture domain-driven-design repository-pattern