委派模式是指对于实现某一行为接口的类,分为委派者和执行者两大类:其中,执行者实现接口中的行为,而委派者实现的功能是选择执行者去执行该行为,委派者和执行者之间为耦合关系。
打个比方,比如有个饭店类需要实现做菜这一接口,饭店中有两个厨子,一个负责甜点,一个负责其他菜(对于做菜接口的不同实现)。因此,饭店需要根据客户点的菜选择不同的厨师进行做菜,此时,饭店就是委派者,而厨子则是执行者。
委派模式的优势在于向外部仅暴露委派者这一个角色,而隐藏了执行者以及执行过程的细节。
#include <iostream>
using namespace std;
class Cook{
virtral void cook(string food);
}
class Restaurant : public Cook {
public:
void cook(string food){
if(food == " cake ") a.cook()
else b.cook();
}
private:
Dessert_chef a;
Other_chef b
}
class Dessert_chef : public Cook{
void cook(string food){
cout<<"I'm a dessert chef, I cook"<<food<<endl;
}
}
class Other_chef : public Cook{
void cook(string food){
cout<<"I am a chef, I cook"<<food<<endl;
}
}
int main(){
Restaurant A;
string food;
while(cin>>food){
A.cook(food);
}
}