版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34784043/article/details/82935559
由于书上的例子不够全面,所以我改写了一下书上的例子。
该模式主要用在给原来的类族添加功能可以不用通过修改原来的类方法,而是通过其他类族来装饰原来的类族,不过这样也会增加代码阅读复杂度。
在下面里,有一个类族,如Person(抽象人类),Mike(叫Mike的人),Jerry(叫Jerry的人),我们想要增加类族中类的功能,比如穿上衣服,可以通过另外一个Finery(服饰抽象类)类族来装饰。
UML:
Person.h
#pragma once
#include <iostream>
class Person {
public:
virtual ~Person(){}
virtual void Show() {};
};
class Mike :public Person {
public:
virtual ~Mike(){}
virtual void Show() {
std::cout << "你好,我是Mike!" << std::endl;
}
};
class Jerry :public Person {
public:
virtual ~Jerry(){}
virtual void Show() {
std::cout << "你好,我是Jerry!" << std::endl;
}
};
Finery.h
#pragma once
#include "Person.h"
//服饰类
class Finery :public Person {
protected:
Person *component;
public:
virtual ~Finery(){delete component;}
void Decorate(Person* component) {
this->component = component;
}
virtual void Show() {
if (component != NULL) {
component->Show();
}
}
};
//具体服饰类
class TShirts :public Finery {
public:
virtual ~TShirts(){}
virtual void Show() {
Finery::Show();
std::cout << "我穿上了T-Shirt" << std::endl;
}
};
class BigTrouser :public Finery {
public:
virtual ~BigTrouser(){}
virtual void Show() {
Finery::Show();
std::cout << "我穿上了垮裤" << std::endl;
}
};
class Sneakers :public Finery {
public:
virtual ~Sneakers(){}
virtual void Show() {
Finery::Show();
std::cout << "我穿上了破球鞋" << std::endl;
}
};
main.cpp
#include "Finery.h"
#include <cstdlib>
int main() {
Person* xc = new Mike();//初始化为Mike
//装饰过程
Finery* pqx = new Sneakers();
pqx->Decorate(xc);
Finery* kk = new BigTrouser();
kk->Decorate(pqx);
Finery* dtx = new TShirts();
dtx->Decorate(kk);
dtx->Show();
delete xc;
delete pqx;
delete kk;
delete dtx;
system("pause");
return 0;
}
运行结果:
扫描二维码关注公众号,回复:
3482085 查看本文章