Python实现工厂模式
from abc import ABCMeta, abstractmethod
from enum import Enum
class 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:
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())
摘自:wiki
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号