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

Python设计模式——状体模式

时间:2014-10-22 23:16:12      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   sp   div   on   log   代码   

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

#encoding=utf-8
__author__ = kevinlu1010@qq.com

def 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.com

from abc import ABCMeta, abstractmethod


class State():
    __metaclass__ = ABCMeta

    @abstractmethod
    def write_code(self):
        pass


class 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设计模式——状体模式

标签:style   blog   color   for   sp   div   on   log   代码   

原文地址:http://www.cnblogs.com/Xjng/p/4044399.html

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