add Decorator Pattern

master
FengJungle 2019-10-25 00:02:47 +08:00
parent be358a9bd3
commit c0ab6ab5fe
6 changed files with 135 additions and 1 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

View File

@ -0,0 +1,93 @@
#ifndef __DECORATOR_PATTERN_H__
#define __DECORATOR_PATTERN_H__
//抽象构件
class Component
{
public:
Component(){}
virtual void operation() = 0;
};
//具体构件类
class Phone :public Component
{
public:
Phone(){}
void operation(){
printf("手机\n");
}
};
//抽象装饰类
class Decorator :public Component
{
public:
Decorator(){}
Decorator(Component *c){
this->component = c;
}
void operation(){
this->component->operation();
}
Component *getComponent(){
return this->component;
}
void setComponent(Component *c){
this->component = c;
}
private:
Component *component;
};
//具体装饰类:手机壳
class DecoratorShell:public Decorator
{
public:
DecoratorShell(){}
DecoratorShell(Component *c){
this->setComponent(c);
}
void operation(){
this->getComponent()->operation();
this->newBehavior();
}
void newBehavior(){
printf("装手机壳\n");
}
};
//具体装饰类:手机贴纸
class DecoratorSticker :public Decorator
{
public:
DecoratorSticker(){}
DecoratorSticker(Component *c){
this->setComponent(c);
}
void operation(){
this->getComponent()->operation();
this->newBehavior();
}
void newBehavior(){
printf("贴卡通贴纸\n");
}
};
//具体装饰类:手机挂绳
class DecoratorRope :public Decorator
{
public:
DecoratorRope(){}
DecoratorRope(Component *c){
this->setComponent(c);
}
void operation(){
this->getComponent()->operation();
this->newBehavior();
}
void newBehavior(){
printf("系手机挂绳\n");
}
};
#endif //__DECORATOR_PATTERN_H__

View File

@ -0,0 +1,37 @@
#include <iostream>
#include "DecoratorPattern.h"
int main()
{
printf("\nJungle的第一个手机\n");
Component *c;
Component *com_Shell;
c = new Phone();
com_Shell = new DecoratorShell(c);
com_Shell->operation();
printf("\nJungle的第二个手机\n");
Component *c2;
Component *com_Shell2;
c2 = new Phone();
com_Shell2 = new DecoratorShell(c2);
Component *com_Sticker;
com_Sticker = new DecoratorSticker(com_Shell2);
com_Sticker->operation();
printf("\nJungle的第三个手机\n");
Component *c3;
Component *com_Shell3;
c3 = new Phone();
com_Shell3 = new DecoratorShell(c3);
Component *com_Sticker2;
com_Sticker2 = new DecoratorSticker(com_Shell3);
Component *com_Rope;
com_Rope = new DecoratorRope(com_Sticker2);
com_Rope->operation();
printf("\n\n");
system("pause");
return 0;
}

View File

@ -47,4 +47,8 @@
12.设计模式(十二)——组合模式
博客地址https://blog.csdn.net/sinat_21107433/article/details/102712738
博客地址https://blog.csdn.net/sinat_21107433/article/details/102712738
13.设计模式(十三)——装饰模式
博客地址https://blog.csdn.net/sinat_21107433/article/details/102733023