1, 介绍 装饰模式是一种结构型设计模式,它能在程序运行时,动态地为对象添加新功能,而不改变其结构。在不改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。装饰模式最终的目的就是“装饰”对象,其中装饰抽象类扮演着至关重要的角色,它实现了组件的通用接口,并且使自身抽象化以迫使子类继承,使装饰固定特性的延续与多态化成为可能。 像其他设计模式一样,装饰模式也抽象、封装了软件中存在变化的部分。装饰模式合理地使用类继承和组合的方式,非常灵活地表达了对象之间的依赖关系。装饰模式使用抽象对组件的扩展功能进行封装,装饰者和被装饰者完全隔离开来,这样我们就可以任意地改变装饰者和被装饰者,而不会引起影响。 装饰模式很好的利用了开闭原则,在需要对组件进行扩展。增加新功能时,只要实现一个特性的装饰者,对原有的软件功能结构没有印象概念股,对用户程序也是透明的。 在装饰模式中,装饰者的角色就是抽象类实现,面向抽象编程的好处就是起到了很好的接口隔离作用。 由于类继承是强关联关系,对象组合则是弱关联关系。装饰模式合理地使用了对象组合方式,通过组合灵活扩展组件的功能,所有的扩展功能都是通过组合而非继承获得,这从根本上决定了这种实现是高内聚、低耦合的。 装饰模式的UML类图:
2, 举例 #include <stdio.h> #include <stdlib.h>
// 被装饰者抽象接口Component typedef struct Component { void (*operation)(struct Component *); } Component;
// 被装饰者具体实现ConcreteComponent typedef struct ConcreteComponent { Component base; } ConcreteComponent;
// 具体的被装饰者实现的操作 void concrete_operation(Component *self) { printf('Concrete operation\n'); }
// 装饰者基类 typedef struct Decorator { Component base; Component *decorated; } Decorator;
// 装饰者的操作实现 void decorator_operation(Component *self) { Decorator *decorator = (Decorator *)self; decorator->decorated->operation(decorator->decorated); }
// 具体的装饰者A实现 typedef struct ConcreteDecoratorA { Decorator base; } ConcreteDecoratorA;
// 装饰者A装饰的功能实现 void decorator_a_operation(Component *self) { printf('Excuting decoratorA operation.\n');
//调用父类方法 decorator_operation(self); }
// 具体的装饰者B实现 typedef struct ConcreteDecoratorB { Decorator base; } ConcreteDecoratorB;
// 装饰者B装饰的功能实现 void decorator_b_operation(Component *self) { printf('Excuting decoratorB operation.\n');
//调用父类方法 decorator_operation(self); }
int main() { // 创建被装饰者 ConcreteComponent component = { {concrete_operation} };
// 创建具体的装饰者A ConcreteDecoratorA a = { { { decorator_a_operation }, (Component *)&component } };
// 创建具体的装饰者B ConcreteDecoratorB b = { { { decorator_b_operation }, (Component *)&component } };
// 调用装饰者A的功能 Component *componenta = (Component *)&a; componenta->operation(componenta);
// 调用装饰者B的功能 Component *componentb = (Component *)&b; componentb->operation(componentb);
return 0; } 如上程序,实现了一个被装饰者抽象接口类Component,一个被装饰者抽象接口类的具体实现类ConcreteComponent,一个装饰者基类Decorator,两个装饰者基建类的继承类(装饰者类)ConcreteDecoratorA和ConcreteDecoratorB。其中,ConcreteDecoratorA和ConcreteDecoratorB继承了基本装饰者类Decorator,可以动态地将一个装饰者类附加到被装饰者上。这样在装饰器调用被装饰者功能前会先执行新增的功能。 |
|
来自: 新用户0118F7lQ > 《文件夹1》