我一直在研究用python实现工厂方法设计模式&我得到的大多数示例都是这种形式的。你知道吗
class Cup:
color = ""
# This is the factory method
@staticmethod
def getCup(cupColor):
if (cupColor == "red"):
return RedCup()
elif (cupColor == "blue"):
return BlueCup()
else:
return None
class RedCup(Cup):
color = "red"
class BlueCup(Cup):
color = "blue"
# A little testing
redCup = Cup.getCup("red")
print "%s(%s)" % (redCup.color, redCup.__class__.__name__)
blueCup = Cup.getCup("blue")
print "%s(%s)" % (blueCup.color, blueCup.__class__.__name__)
为什么对工厂函数使用class
?你知道吗
就不能这样:
def CupFactory(cupColor):
if (cupColor == "red"):
return RedCup()
elif (cupColor == "blue"):
return BlueCup()
else:
return None
或者有一个特定的情况,基于类的方法是首选/需要的。你知道吗
注意:互联网上使用类的示例。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐