策略模式包含以下主要角色:
1. 策略接口(Strategy): 定义了算法族的接口,具体的策略类实现了这个接口。
2. 具体策略类(Concrete Strategy): 实现了策略接口,封装了具体的算法。
3. 上下文(Context): 维护一个对策略对象的引用,可以在运行时切换不同的策略。
下面是一个简单的策略模式的例子,假设有一个图像编辑器,用户可以选择不同的滤镜来处理图像:
# 策略接口
class ImageFilterStrategy:
def apply_filter(self, image):
pass
# 具体策略类:黑白滤镜
class BlackAndWhiteFilter(ImageFilterStrategy):
def apply_filter(self, image):
print("Applying Black and White Filter to image")
# 具体策略类:模糊滤镜
class BlurFilter(ImageFilterStrategy):
def apply_filter(self, image):
print("Applying Blur Filter to image")
# 具体策略类:高对比度滤镜
class HighContrastFilter(ImageFilterStrategy):
def apply_filter(self, image):
print("Applying High Contrast Filter to image")
# 上下文类:图像编辑器
class ImageEditorContext:
def __init__(self, filter_strategy):
self._filter_strategy = filter_strategy
def apply_filter(self, image):
self._filter_strategy.apply_filter(image)
def set_filter_strategy(self, filter_strategy):
self._filter_strategy = filter_strategy
# 客户端代码
if __name__ == "__main__":
# 创建图像编辑器上下文,并设置初始滤镜策略
image_editor = ImageEditorContext(BlackAndWhiteFilter())
# 应用滤镜
image_editor.apply_filter("Image1.jpg")
# 切换滤镜策略
image_editor.set_filter_strategy(BlurFilter())
image_editor.apply_filter("Image2.jpg")
# 切换滤镜策略
image_editor.set_filter_strategy(HighContrastFilter())
image_editor.apply_filter("Image3.jpg")
在上述示例中,ImageFilterStrategy 是策略接口,定义了应用滤镜的方法。BlackAndWhiteFilter、BlurFilter、HighContrastFilter 是具体策略类,分别实现了不同的滤镜算法。ImageEditorContext 是上下文类,维护一个对策略对象的引用,并在运行时可以切换不同的滤镜策略。
客户端代码可以通过创建不同的滤镜策略对象,并设置到图像编辑器上下文中,来动态地选择不同的滤镜算法。
策略模式的优点在于它允许客户端代码选择不同的算法,而无需修改现有代码。这种模式使得算法的定义和使用分离,提高了系统的灵活性和可维护性。
转载请注明出处:http://www.zyzy.cn/article/detail/11860/设计模式