返回
灵活开发!掌握简单工厂模式再助你一臂!
前端
2023-10-31 05:21:22
理解简单工厂模式
简单工厂模式可以把对象的创建过程进行抽象化,实现对象的创建方式与具体对象无关。
为什么选择简单工厂模式
- 更加灵活:当我们需要扩展一个系统的时候,添加新类不会破坏既有对象的创建方式,做到低耦合和高灵。
- 更多样貌:可以让用户在多种类型中进行选择,且能清楚知道各个类的区别。
- 简洁易用:通过简单的条件判断就可以创建对象。
简单工厂模式的局限
- 维护困难:随着功能的扩展,类库会日渐庞大,简单工厂模式将难以维护。
- 弹性不佳:简单工厂模式在对象创建上过于依赖 switch 或枚举等结构,灵敏度不高。
一个简单的例子
我们使用简单工厂模式来创建一个对象的工厂,假设这个工厂只创建圆形和正方形。
class ShapeFactory:
def get_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "square":
return Square()
else:
raise ValueError("Invalid shape type.")
class Circle:
def __init__(self):
self.name = "Circle"
self.description = "A circle is a round figure with no corners or edges."
class Square:
def __init__(self):
self.name = "Square"
self.description = "A square is a four-sided figure with equal length sides and right angles."
if __name__ == "__main__":
factory = ShapeFactory()
circle = factory.get_shape("circle")
square = factory.get_shape("square")
print(circle.name, circle.description)
print(square.name, square.description)
在代码中,ShapeFactory 类是一个工厂类,用 get_shape() 方法来创建形状对象。Circle 和 Square 类分别表示圆形和正方形的实现。
总结
简单工厂模式作为一种基础设计模式,有其优点也有局限,但也更适用于模块化和容易预测需求的系统中。希望这篇文章能让你我更加了解并能灵活使用简单工厂模式。若需更多信息,可以通过搜索引擎进一步探索。