Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses.
“工厂模式”:通过接口的方式__间接__调用(那些)类来创建对象;该接口通常用函数、类或类的静态方法来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 ''' Python示例代码,来自网络 ''' from abc import ABCMeta, abstractmethodfrom enum import Enumclass Person : __metaclass__ = ABCMeta @abstractmethod def get_name (self ): raise NotImplementedError("You should implement this!" ) class Villager (Person ): def get_name (self ): return "Village Person" class CityPerson (Person ): def get_name (self ): return "City Person" class PersonType (Enum ): RURAL = 1 URBAN = 2 class Factory (object ): def get_person (self, person_type ): if person_type == PersonType.RURAL: return Villager() elif person_type == PersonType.URBAN: return CityPerson() else : raise NotImplementedError("Unknown person type." ) factory = Factory() person = factory.get_person(PersonType.URBAN) print(person.get_name())