#责任链模式
#自定义请求东西,目前请求的是温度
class Request():
def __init__(self,temprature):
self.__temprature=temprature
def getTemprature(self):
return self.__temprature
class Responsible():
def __init__(self):
self.__nextHandler=None
def setNextHandler(self,handler):
self.__nextHandler=handler
def getNextHandler(self):
return self.__nextHandler
def handleRequest(self,request):
if(self.__nextHandler is not None):
self.handleRequest(request)
class Gas(Responsible):
def __init__(self):
super().__init__()
def handleRequest(self,request):
if(request.getTemprature()>100):
print("i'm gas")
if(self.getNextHandler() is not None):
self.getNextHandler().handleRequest(request)
class Liquid(Responsible):
def __init__(self):
super().__init__()
def handleRequest(self,request):
if(request.getTemprature()>0 and request.getTemprature()<100):
print("i'm liquid")
if(self.getNextHandler() is not None):
self.getNextHandler().handleRequest(request)
class Water():
def __init__(self):
self.__leader=None
def sendRequest(self,request):
self.__leader.handleRequest(request)
def setLeader(self,leader):
self.__leader=leader
gas = Gas()
gas.setNextHandler(Liquid())
t=Water();
t.setLeader(gas)
request=Request(22)
t.sendRequest(request)
本质就Requester发送request,然后交给Responsible处理,如果有下一个责任人则继续往下传