#include<iostream>
using namespace std;
class Order
{
public:
virtual void printOrder() {cout << "订单内容!" << endl; }
};
class Decorator:public Order //(1)
{
private:
Order *order;
public:
Decorator(Order *order)
{
this->order = order; //(2)
}
void printOrder()
{
if(order != NULL)
{
order->printOrder();
}
}
};
class HeadDecorator:public Decorator
{
public:
HeadDecorator(Order *order):Decorator(order) //(3)
{
}
void printOrder()
{
cout << "订单抬头!" << endl;
Decorator::printOrder();
}
};
class FootDecorator:public Decorator
{
public:
FootDecorator(Order *order):Decorator(order) //(4)
{
}
void printOrder()
{
Decorator::printOrder(); //(5)
cout << "订单脚注!" << endl;
}
};
class PrintOrder: public Order//(6)
{
private:
Order *order;
public:
PrintOrder(Order *order)
{
this->order = order; //(7)
}
void printOrder()
{
FootDecorator *foot = new FootDecorator(order);
HeadDecorator *head = new HeadDecorator(order);
head->printOrder();
cout << "----------------------" << endl;
FootDecorator foot1(NULL);
HeadDecorator head1(&foot1);
head1.printOrder();
}
};
int main()
{
Order *order = new Order();
Order *print = new PrintOrder(order);
print->printOrder();
}
答案:
(1) : public Order
(2) this->order 或 (*this).order
(3) Decorator(order)
(4) Decorator(order)
(5) Decorator::printOrder()
(6) : public Order
(7) this->order 或 (*this).order
网友评论