欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > asp.net >内容正文

asp.net

设计模式复习-装饰模式

发布时间:2025/6/17 asp.net 14 豆豆
生活随笔 收集整理的这篇文章主要介绍了 设计模式复习-装饰模式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1. Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteComponent就是具体的装饰对象,起到给Component添加职责的功能。

 

2. 装饰模式是利用SetComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。

3. 如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类,同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。


代码:

#pragma once #include "stdafx.h" #include<iostream> #include<windows.h> using namespace std;class Component { public:virtual VOID Operator() = 0; };class ConcreteComponent :public Component { public:VOID Operator() {cout << "具体操作对象" << endl;} };class Decorator :public Component { private:Component * mpComponent = NULL; public:VOID SetComponent(Component * pComponent) {mpComponent = pComponent;}VOID Operator() {if (mpComponent != NULL) {mpComponent->Operator();}} };class ConcreteDecoratorA :public Decorator { public:VOID Operator() {Decorator::Operator();cout << "具体装饰对象A的操作" << endl;} };class ConcreteDecoratorB :public Decorator { public:VOID Operator() {Decorator::Operator();cout << "具体装饰对象B的操作" << endl;} };int main() {ConcreteComponent *pPeople = new ConcreteComponent(); //定义一个人ConcreteDecoratorA *pClothesA = new ConcreteDecoratorA();//A衣服ConcreteDecoratorB *pClothesB = new ConcreteDecoratorB();//B衣服pClothesA->SetComponent(pPeople); //穿A衣服pClothesB->SetComponent(pClothesA);//继续穿上B衣服pClothesB->Operator(); //showtimedelete pPeople, delete pClothesA, delete pClothesB;getchar();return 0; }

 

总结

以上是生活随笔为你收集整理的设计模式复习-装饰模式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。