1. 程式人生 > >設計模式 狀態模式

設計模式 狀態模式

class WorkState:
    def __init__(self):
        pass
    def work(self):
        pass

class Monday(WorkState):
    def work(self, w):
        if w.day == 1:
            print('no happy')
        else:
            w.setState(TueToFri())
            w.work()

class TueToFri(WorkState):
    def work(self, w):
        
if w.day > 1 and w.day < 6: print('little happy') else: w.setState(Weekend()) w.work() class Weekend(WorkState): def work(self, w): if w.day >= 6 and w.day <= 7: print('happy') else: w.setState(NoVailidDay()) w.work()
class NoVailidDay(WorkState): def work(self, w): if w.day > 7: print('no valid day') class Context: state = Monday() day = 2 def setState(self, state): self.state = state def work(self): self.state.work(self) if __name__ == '__main__': context
= Context() context.work()