我是一名C#程序员,我希望建立一个简单的工厂。遵守命令:
class ShapeFactory:
_registry: Dict[ShapeType, Shape] = {
ShapeType.Shape: lambda: Shape(),
ShapeType.Circle: lambda: Circle(),
ShapeType.Square: lambda: Square()
}
def Create(self, key: ShapeType) -> Shape:
if key in self._registry:
return self._registry.get(key)
raise KeyError(key)
def Register(self, key: ShapeType, value: Shape) -> None:
if key not in self._registry:
self._registry[key] = value
raise KeyError(type)
问题是Create
总是返回相同的实例,例如,Circle
。如何在允许OCP的同时实现动态实例化对象的方法
编辑: 进一步阐述我的观点;在C#中,我将我的字典声明为:
Dictionary<ShapeType, Func<Shape>> _registry = new Dictionary{
[ShapeType.Shape] = () => new Shape(),
[ShapeType.Circle] = () => new Circle(),
[ShapeType.Square] = () => new Square()
}
这将始终为字典的每个值返回一个新实例化的对象。这就是我希望在python中重现的效果
您在这个设计中遇到了一些更大的问题
首先,如果类中有一个可变属性,那么应该在类的
__init__
方法中定义_registry
(与实例隔离)接下来,
_registry
的type属性是错误的。您有dict
个lambda
,而不是Shape
个实例。你需要Dict[ShapeType, Callable[[], Shape]]
。Register
方法也有类似的问题您还应该遵循PEP 8的命名规则。试试这个:
动态创建对象的简单python方法是:
相关问题 更多 >
编程相关推荐