工厂设计模式的实现?

2024-10-03 13:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究用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

或者有一个特定的情况,基于类的方法是首选/需要的。你知道吗

注意:互联网上使用类的示例。你知道吗

Example 1.
Example 2


Tags: 方法示例return工厂blueredclasscolor