python 实现工厂类方法

lanjianhua / 2024-10-13 / 原文


# 工厂类方法1,这些类的实例方法名 相同
class Fruit(object):
    def __init__(self):
        pass

    def print_color(self):
        pass

# 工厂类方法2
class Apple(Fruit):
    def __init__(self):
        pass

    def print_color(self):
        print("apple is in red")

# 工厂类方法3
class Orange(Fruit):
    def __init__(self):
        pass

    def print_color(self):
        print("orange is in orange")


# 管理类
class FruitFactory(object):
    fruits = {"apple": Apple, "orange": Orange}

    def __new__(cls, name):
        if name in cls.fruits.keys():
            return cls.fruits[name]()
        else:
            return Fruit()

fruit1 = FruitFactory("apple")
fruit2 = FruitFactory("orange")
fruit1.print_color()    # 输出: apple is in red 
fruit2.print_color()    # 输出: orange is in orange