装饰器模式允许在不改变原有类的前提下,动态地给一个类添加新的功能。它通过创建一系列装饰器类,这些类与原始对象具有相同的接口,可以在不改变原始对象的情况下,增加、扩展或修改其功能。而代理模式则是控制对对象的访问,为对象生成一个代理类,由代理类去调用被代理类的方法并添加一些逻辑。两者的主要区别在于目的和使用场景的不同。装饰器模式更注重于动态地增强对象的功能,而不改变其结构;而代理模式则更侧重于控制对对象的访问和操作。
本文目录导读:
简介
装饰器模式是一种结构型设计模式,它允许在不改变原有类的前提下,为一个类添加新的功能,这种模式通常用于动态地给对象添加额外的职责,如果我们有一个Person
类,我们可以使用装饰器模式来为其添加一个新的方法,如sayHello()
。
实现步骤
2.1 定义装饰器接口
我们需要定义一个装饰器接口,该接口包含一个用于添加新功能的装饰器方法,这个方法可以是一个静态方法或者一个实例方法,具体取决于需求。
class Decorator: def __init__(self, target): self.target = target def __call__(self, *args, **kwargs): if not hasattr(self.target, '__decorated_methods'): self.target.__decorated_methods = set() # 将目标方法添加到已装饰方法集合中 self.target.__decorated_methods.add(self.target) # 调用目标方法 result = self.target(*args, **kwargs) # 从已装饰方法集合中移除当前方法 self.target.__decorated_methods.remove(self.target) return result
2.2 定义被装饰的类
我们需要定义一个被装饰的类,该类包含一个或多个方法,这些方法将被装饰器添加到__decorated_methods
属性中。
class Person: def sayHello(self): print("Hello, world!") def greet(self): print("Hello, {}!".format(self.name)) def name(self): return "World"
2.3 创建装饰器实例
我们可以创建装饰器实例,并使用它来装饰被装饰的类的方法。
创建一个装饰器实例 decorator = Decorator(Person) 使用装饰器实例来装饰Person类的sayHello方法 person = Person() result = decorator(person, sayHello)()
示例
假设我们有一个Student
类,我们希望为其添加一个新的方法attendClass
,该方法可以在上课时提醒学生,我们可以使用装饰器模式来实现这个功能。
class AttendanceNotifier: def __init__(self, student): self.student = student def attendClass(self, message): print(message) class Student: def __init__(self): self.notified = False def notify(self, message): if not self.notified: AttendanceNotifier(self).attendClass(message) self.notified = True def classTime(self): print("It's time to attend class!")
在这个示例中,我们使用了装饰器模式来为Student
类添加了一个新的方法notify
,该方法可以在上课时提醒学生,通过这种方式,我们可以在不修改原有类的情况下为类添加新的职责。