常见的使用修饰符的场景是每个函数都有一段相同的逻辑,提取出来作为修饰符,那个比较常见,下面的例子是另外一个比较常见的使用修饰符的场景,可以提高代码可维护性。
有多种消息类型,每个类型对应一个消息类,新增消息类怎么添加到原先的代码逻辑呢,使用一堆if么
message_type = message["type"]
if message_type == "text":
TextMessage(message).handle()
elif message_type == "voice":
VoiceMessage(message).handle()
else:
UnknownMessage(message).handle()
这样肯定可以,但是降低了代码可维护性,每次都要修改,太麻烦了。
这里我们可以使用修饰符了~
# coding=utf-8
MESSAGE_CLASSES = {}
def handle_for_message_types(message_type):
def register(cls):
MESSAGE_CLASSES[message_type] = cls
return cls
return register
class BaseMessage(object):
def __init__(self, message):
self.message = message
@handle_for_message_types("text")
class TextMessage(BaseMessage):
def handle(self):
print "text messsage"
@handle_for_message_types("voice")
class VoiceMessage(BaseMessage):
def handle(self):
print "voice message"
@handle_for_message_types("unknown")
class UnknownMessage(BaseMessage):
def handle(self):
print "unknown message"
def parse_message(message):
cls = MESSAGE_CLASSES.get(message["type"], UnknownMessage)
cls(message).handle()
parse_message({"type": "text", "content": "Hello world"})
parse_message({"type": "voice", "content": "http://xxx.com/voice.mp3", "length": 10})
parse_message({"type": "new_type", "content": "balabala"})
每次只增加代码就可以了,不用修改老代码~
里面的类修饰符相当于
@addID
class Foo:
pass
class Foo:
pass
Foo = addID(Foo)