本文實(shí)例講述了Python設(shè)計(jì)模式之狀態(tài)模式原理與用法。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的太子河網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!狀態(tài)模式(State Pattern):當(dāng)一個(gè)對(duì)象的內(nèi)在狀態(tài)改變時(shí)允許改變其行為,這個(gè)對(duì)象看起來像是改變了其類
下面是一個(gè)狀態(tài)模式的demo:
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Andy' """ 大話設(shè)計(jì)模式 設(shè)計(jì)模式——狀態(tài)模式 狀態(tài)模式(State Pattern):當(dāng)一個(gè)對(duì)象的內(nèi)在狀態(tài)改變時(shí)允許改變其行為,這個(gè)對(duì)象看起來像是改變了其類 應(yīng)用場(chǎng)景:當(dāng)控制一個(gè)對(duì)象的狀態(tài)轉(zhuǎn)換的條件表達(dá)式過于復(fù)雜時(shí),把狀態(tài)的判斷邏輯轉(zhuǎn)移到表示不同狀態(tài)的一系列類當(dāng)中,可以把復(fù)雜的判斷邏輯簡(jiǎn)化 (當(dāng)一個(gè)對(duì)象的行為取決于它的狀態(tài),并且它必須在運(yùn)行時(shí)刻根據(jù)狀態(tài)改變他的行為) """ class State(object): def __init__(self): pass def write_program(self, w): pass class Work(object): def __init__(self): self.hour = 9 self.curr = ForenoonState() def set_state(self, s): self.curr = s def write_program(self): self.curr.write_program(self) class ForenoonState(State): def write_program(self, w): if w.hour < 12: print "當(dāng)前時(shí)間:%s點(diǎn),"%w.hour,"精神百倍" else: w.set_state(AfternoonState()) w.write_program() class AfternoonState(State): def write_program(self, w): if w.hour < 17: print "當(dāng)前時(shí)間:%s點(diǎn),"%w.hour,"狀態(tài)還行,繼續(xù)努力" else: w.set_state(EveningState()) w.write_program() class EveningState(State): def write_program(self, w): if w.hour < 21: print "當(dāng)前時(shí)間:%s點(diǎn),"%w.hour,"加班呢,疲勞了" else: w.set_state(SleepState()) w.write_program() class SleepState(State): def write_program(self, w): print "當(dāng)前時(shí)間:%s點(diǎn),"%w.hour,"不行了,睡著了" if __name__=="__main__": work = Work() work.hour = 9 work.write_program() work.hour = 15 work.write_program() work.hour = 20 work.write_program() work.hour = 22 work.write_program()