python实现工厂模式

我们有一个基类Person,包含方法get_name和get_gender 。有两个子类Male 和Female,构造函数可以打招呼。还有一个工厂类。工厂类有一个方法名get_person有两个输入参数,名字和性别。
用户使用工厂类,通过调用get_person方法。

在程序运行期间,用户通过性别传递来决定实例为Male还是Female。

class Person:
    name = None
    gender = None

    def __init__(self):
        pass

    def get_name(self):
        return self.name

    def get_gender(self):
        return self.gender


class Male(Person):
    def __init__(self, name):
        super(Male).__init__()
        self.gender = "Male"
        self.name = name
        print("Hello Mr.{}".format(name))


class Female(Person):
    def __init__(self, name):
        super(Female).__init__()
        self.gender = "Female"
        self.name = name
        print("Hello Miss.{}".format(name))


class Factory:
    def get_person(self, name, gender):
        if gender == "M":
            return Male(name)
        elif gender == "F":
            return Female(name)
        else:
            raise Exception("please input 'M' or 'F'")


GENDER = "F"

if __name__ == '__main__':
    factory = Factory()
    person = factory.get_person("Lee", GENDER)
    print(person.get_name())
    print(person.get_gender())

输出:


Hello Miss.Lee
Lee
Female

你可能感兴趣的:(python,工厂模式)