python工厂模式代码示例

直接复制下述代码并运行,环境为python 3.5

import sys


class Employee:
    @staticmethod
    def create(class_type):
        current_module = sys.modules[__name__]
        class_name = getattr(current_module, class_type)
        return class_name()


class Engineer(Employee):
    pass


class SalesMan(Employee):
    pass


class Manager(Employee):
    pass


en = Employee.create('Engineer')
ma = Employee.create('Manager')
print(type(en), type(ma))

参考资料:

  1. Python: How do I get a reference to a module inside the module itself?
  2. Does python have an equivalent to Java Class.forName()?
  3. How to create an object instance from a string??

你可能感兴趣的:(Python)