首页 > 代码库 > Python设计模式——状体模式

Python设计模式——状体模式

需求,根据当前的时间,返回工作状态

#encoding=utf-8__author__ = kevinlu1010@qq.comdef get_state(hour):    if hour>=8 and hour<=12:        return 上午工作,精神百倍    elif hour>12 and hour<=14:        return 中午工作,困,想午休    elif hour>14 and hour<=18:        return 下午工作,状态不错    elif hour>18 and hour<=20:        return 加班了,状态不太好    else:        return 不行了,要睡觉了if __name__==__main__:    for hour in (9,11,12,13,14,17,19,22,23):        print %d点,%hour,get_state(hour)

缺点是,如果状态非常多时,(现在是5种),这段代码将会非常长,所以后期维护就比较困难

状态模式

#encoding=utf-8__author__ = kevinlu1010@qq.comfrom abc import ABCMeta, abstractmethodclass State():    __metaclass__ = ABCMeta    @abstractmethod    def write_code(self):        passclass Morning(State):    def write_code(self, work):        if work.hour <= 12 and work.hour > 8:            print 上午工作,精神百倍        else:            work.set_status(Noon())            work.write_code(work)class Noon(State):    def write_code(self, work):        if work.hour <= 14 and work.hour>12 :            print 中午工作,困,想午休        else:            work.set_status(Afternoon())            work.write_code(work)class Afternoon(State):    def write_code(self, work):        if work.hour <= 18 and work.hour>14:            print 下午工作,状态不错        else:            work.set_status(Eve())            work.write_code(work)class Eve(State):    def write_code(self, work):        if work.hour <= 22 and work.hour>18:            print 加班了,状态不太好        else:            work.set_status(Night())            work.write_code(work)class Night(State):    def write_code(self, work):        if work.hour <= 8 or work.hour > 22:            print 不行了,要睡觉了        else:            work.set_status(Morning())            work.write_code(work)class Work():    def __init__(self, hour):        self.hour = hour        self.state = Morning()    def set_status(self, state):        self.state = state    def write_code(self, work):        self.state.write_code(work)if __name__ == __main__:    work = Work(10)    for hour in (9, 11, 12, 13, 14, 17, 19, 22, 23,12):        work.hour = hour        print %d点, % hour        work.write_code(work)

 

状态模式中,定义一个状态的抽象类,为每一种状态建一个类,类中有一个handle函数(这里是write_code),来根据work的时间来做相应的处理,这种做的好处是十分灵活,每个状态都有自己的判断逻辑。拓展和维护起来都比较方便。

 

Python设计模式——状体模式