我试图了解对责任链模式的理解,作为练习,我编写了一些代码。这段代码
class SomeObject:
def __init__(self):
self.integer_field = 0
self.float_field = 0.0
self.string_field = 'hi'
class EventGet:
def __init__(self, data_type):
self.data_type = data_type
class EventSet:
def __init__(self, value):
self.value = value
class NullHandler:
def __init__(self, successor=None):
self.__successor = successor
def handle(self, obj, event):
if self.__successor:
self.__successor.handle(obj, event)
class IntHandler(NullHandler):
def handle(self, obj, event):
if isinstance(event, EventGet) and event.data_type is int:
return obj.integer_field
elif isinstance(event, EventSet) and isinstance(event.value, int):
obj.integer_field = event.value
else:
super().handle(obj, event)
class FloatHandler(NullHandler):
def handle(self, obj, event):
if isinstance(event, EventGet) and event.data_type is float:
return obj.float_field
elif isinstance(event, EventSet) and isinstance(event.value, float):
obj.float_field = event.value
else:
super().handle(obj, event)
class StrHandler(NullHandler):
def handle(self, obj, event):
if isinstance(event, EventGet) and event.data_type is str:
return obj.string_field
elif isinstance(event, EventSet) and isinstance(event.value, str):
obj.string_field = event.value
else:
super().handle(obj, event)
但是它不符合我的预期。通过以下方式被调用
obj = SomeObject()
chain = IntHandler(FloatHandler(StrHandler(NullHandler())))
print(chain.handle(obj, EventGet(int)))
print(chain.handle(obj, EventGet(float)))
print(chain.handle(obj, EventGet(str)))
chain.handle(obj, EventSet(1))
print(obj.integer_field)
chain.handle(obj, EventSet(1.1))
print(obj.float_field)
chain.handle(obj, EventSet('str'))
print(obj.string_field)
它会产生令人困惑的输出:
0 # That's ok
None # Why not 0.0?
None # Why not hi?
1 # That's ok
1.1 # That's ok
str # That's ok
我不知道为什么调用chain.handle(obj, EventGet(float))
和chain.handle(obj, EventGet(str))
会产生None
。毕竟,在相应位置(即return
和return obj.float_field
)有一个return obj.string_field
语句。
能否请您向我解释此代码中的错误以及如何使其按预期工作?提前非常感谢!