我有一个关于 C++ 中装饰器模式工作的问题。考虑以下场景(我从网上得到的。抱歉,我不能把问题缩小,因为我必须提供所有细节。)
class print{
public:
virtual ~print(){};
virtual void print_name() = 0;
};
//Actual base class which is to be used for printing. Has only name
class name:public print{
public:
//Destructor
~name() { cout << "destructing name" << endl; }
void print_name(){
cout << "Ajay " << endl;
}
};
class decorator:public print{
print *print_content;
public:
//constructor
decorator(print* print_arg){
print_content = print_arg;
}
//Destructor
~decorator() {
if(print_content){
delete print_content;
print_content = NULL;
}
}
void print_name(){
print_content->print_name();
}
};
class surname:public decorator{
public:
//Constructor
surname( print * print_arg ):decorator(print_arg) {}
//Destructor
~surname(){
cout << "Destructing surname" << endl;
}
void print_name(){
cout << " Bidari" << endl;
decorator::print_name();
}
};
class address:public decorator{
public:
address( print * print_arg):decorator(print_arg) {}
~address(){
cout <<"Destructing address" << endl;
}
void print_name(){
cout << "Bijapur" << endl;
decorator::print_name();
}
};
所有类都具有装饰设计模式所需的语义。主要功能如下。
int main(){
print * name_surname_address = new address(new surname(new name));
name_surname_address->print_name();
}
程序按预期打印结果。
输出
Bidari
Ajay
Bijapur
Bidari
Ajay
我不明白这个电话是如何进入 surname::print_name() 的。我的意思是函数调用
print * name_surname_address = new address(new surname(new name));
调用地址的 print_name,该地址调用 decorator::print_name(),后者又调用 print::print_name()。