码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现工厂模式

时间:2018-01-19 22:26:17      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:工厂   error   urb   targe   bst   you   else   href   ref   

 

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

设计模式

 

Python实现工厂模式

标签:工厂   error   urb   targe   bst   you   else   href   ref   

原文地址:https://www.cnblogs.com/standby/p/8318821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!