#include <iostream>
using namespace std;
class Component
{
public:
virtual void prtTicket() = 0;
};
class SalesTicket:public Component
{
public:
void prtTicket()
{
cout << "SalesTicket::PrtTicket" << endl;
}
};
class Decorator : public Component
{
public:
void prtTicket()
{
if (myComp != 0)
myComp->prtTicket();
}
Decorator( Component *myC)
{
myComp = myC;
}
private:
Component * myComp;
};
class Header1 : public Decorator
{
public:
Header1(Component *myC):Decorator(myC){}
void prtTicket()
{
cout << "Header1" << endl;
Decorator::prtTicket();
}
};
class Header2 : public Decorator
{
public:
Header2(Component *);
void prtTicket()
{
cout << "Header2" << endl;
Decorator::prtTicket();
}
};
class Footer1 : public Decorator
{
public:
Footer1(Component *myC):Decorator(myC){}
void prtTicket()
{
Decorator::prtTicket();
cout << "Footer1" << endl;
}
};
class Footer2 : public Decorator
{
public:
Footer2(Component *);
void prtTicket()
{
Decorator::prtTicket();
cout << "Footer2" << endl;
}
};
class Configuration
{
private:
Header1 *hd1;
Header2 *hd2;
Footer1 *ft1;
Footer2 *ft2;
public:
Configuration()
{
/*
hd1 = new Header1; //
hd2 = new Header2;
ft1 = new Footer1;
ft2 = new Footer2;*/
}
~Configuration()
{
/*
delete hd1;
delete hd2;
delete ft1;
delete ft2;*/
}
public:
static Component* getsalesTicket()
{
return new Header1(
new Footer1(
new SalesTicket
)
);
}
};
class SalesOrder
{
public:
void prtTicket()
{
Component *myST;
myST = Configuration::getsalesTicket();
myST->prtTicket();
}
};
using namespace std;
int
main()
{
SalesOrder so;
so.prtTicket();
//Header1 * hd1 = new Header1(new SalesTicket);
return 0;
}
本文通过一个具体的例子展示了装饰者模式在C++中的实现过程。该模式允许在不修改原始类的情况下增加职责或行为,通过继承和组合的方式,将额外的功能附加到对象上。文章详细解释了如何使用装饰者模式来扩展销售票据打印功能。
305

被折叠的 条评论
为什么被折叠?



