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

python状态模式实现状态切换

时间:2018-01-25 13:10:06      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:rac   self   col   odi   bsp   nbsp   log   状态模式   切换   

# -*- coding:UTF-8 -*-
import abc


class State(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def handle(self, context):
        pass


class ConcreteStateA(State):
    def handle(self, context):
        context.state = ConcreteStateB()


class ConcreteStateB(State):
    def handle(self, context):
        context.state = ConcreteStateA()


class Context:
    def __init__(self, state):
        self.__state = state

    @property
    def state(self):
        return self.__state

    @state.setter
    def state(self, value):
        self.__state = value
        print("当前状态:%s" % self.__state.__class__.__name__)

    def request(self):
        self.__state.handle(self)


if __name__ == "__main__":
    c = Context(ConcreteStateA())
    c.request()
    c.request()
    c.request()
    c.request()
    c.request()

 

python状态模式实现状态切换

标签:rac   self   col   odi   bsp   nbsp   log   状态模式   切换   

原文地址:https://www.cnblogs.com/gjinwei/p/8350598.html

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