python state mode

What is the status mode?

It refers to the internal state of the object changes the object's behavior will change.
State mode main solution is a state of the object when the control conditional expression is too complex situations. Determining the logic state proceeds to a state represented by a series of different classes, can simplify the complex decision logic.

UML class diagrams

 

 

 

Change package

The mode status is changed, the change was made part of the abstract class or interface, which makes the aim to do is to change into a stable

The sample code

import abc

'''
例子:灯的状态
'''


class AbsStatus(abc.ABC):

    @abc.abstractmethod
    def action(self, context): ...


class Bulb:
    def __init__(self, status: AbsStatus):
        self._status = status

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, value: AbsStatus):
        self._status = value

    def action(self):
        self.status.action(self)


class OnStatus(AbsStatus):

    DEF Action (Self, context):
         Print ( " Current status: turn " ) 
        context.status = OffStatus () 


class OffStatus (AbsStatus): 

    DEF Action (Self, context):
         Print ( " Current Status: lights " ) 
        context .status = onStatus () 


Buld = Bulb (OffStatus ()) 
buld.action () # current status: lights 
buld.action () # current status: turn 
buld.action () # current status: turn off the lights 
buld.action () # current status: turn on the lights

 

Guess you like

Origin www.cnblogs.com/whnba/p/12003974.html