python設計模式狀態模式

為不為發表於2019-01-03
class State:
    def __init__(self,name):
        self.__name=name
    def getStateName(self):
        return self.__name
    def behavior(self,water):
        pass
class SolidState(State):
    def __init__(self,name):
        super().__init__(name)
    def behavior(self,water):
        print("cold",water.getTemperature())
class LiquidState(State):
    def __init__(self,name):
        super().__init__(name)
    def behavior(self,water):
        print("liquid",water.getTemperature())
class Gas(State):
    def __init__(self,name):
        super().__init__(name)
    def behavior(self,water):
        print("gas",water.getTemperature())
class Water:
    def __init__(self,state):
        self.__temperature=25
        self.__state=state
    def setState(self,state):
        self.__state=state
    def changeState(self,state):
        if(self.__state):
            print("狀態變更",self.__state.getStateName(),"變為",state.getStateName())
        else:
            print("初始化",state.getStateName())
        self.__state=state
    def getTemperature(self):
        return self.__temperature
    def setTemperature(self,temperature):
        self.__temperature=temperature
        if(self.__temperature<=0):
            self.changeState(SolidState("solid"))
        elif(self.__temperature<=100 and self.__temperature>0):
            self.changeState(LiquidState("liquid"))
        elif(self.__temperature>100):
            self.changeState(Gas("gas"))
    def addTemperature(self,temp):
        self.setTemperature(self.__temperature+temp)
    def reduceTemperature(self,temp):
        self.setTemperature(self.__temperature-temp)
    def behavior(self):
        self.__state.behavior(self)

t=Water(LiquidState("liquid"))
t.behavior()
t.addTemperature(80)
t.behavior()

相關文章