某咖啡店当卖咖啡时,可以根据顾客的要求在其中加入各种配料,咖啡店会根据所加入的配料来计算费用。咖啡店所供应的咖啡及配料的种类和价格如下表所示。

现采用装饰器(Decorator)模式来实现计算费用的功能,得到如图5-1所示的类图

【C++代码】
#include<iostream>
#include<string>
using namespace std;
const int ESPRESSO_PRICE=25;
const int DRAKROAST_PRICE=20;
const int MOCHA_PRICE=10;
const int WHIP_PRICE=8;
class Beverage{//饮料
(1):string description;
public:
(2)( ){return description;}
(3);
};
class CondimentDecorator:public Beverage{//配料
protected:
(4);
};
class Espresso:public Beverage{//蒸馏咖啡
public:
Espresso( ){description="Espresso";}
int cost( ){return ESPRESSO_PRICE;}
};
class DarkRoast:public Beverage{//深度烘焙咖啡
public:
DarkRoast( ){description="DardRoast";}
int cost( ){return DRAKROAST_PRICE;}
};
class Mocha:public CondimentDecorator{//摩卡
public:
Mocha(Beverage*beverage){this->beverage=beverage;}
string getDescription( ){return beverage->getDescription( )+",Mocha";}
int cost( ){return MOCHA_PRICE+beverage->cost( );}
};
class Whip:public CondimentDecorator{//奶泡
public:
Whip(Beverage*beverage){this->beverage=beverage;}
string getDescription( ){return beverage->getDescription( )+",Whip";}
int cost( ){return WHIP_PRICE+beverage->cost( );}
};
int main( ){
Beverage*beverage=new DarkRoast( );
beverage=new Mocha((5));
beverage=new Whip((6));
cout<<beverage->getDescription( )<<"¥"<<beverage->cost( )endl;
return 0;
}
编译运行上述程序,其输出结果为:
DarkRoast,Mocha,Whip¥38
正确答案及解析
正确答案
解析
(1)protected
(2)virtual string getDescription
(3)virtual int cost()=0
(4)Beverage*beverage
(5)beverage
(6)beverage
本题考查了C++语言的应用能力和装饰设计模式的应用。
第(1)空很明显,是要说明属性description在类Beverage中的类型,应该是私有的、受保护的或公有的,从后面的程序我们可以看出,子类中继承使用了该属性,因此这里只能定义为受保护的,因此第(1)空的答案为protected。
第(2)空处也很明显,是要给出一个函数的定义,并且该函数的函数体是“return description;”,从子类奶泡和摩卡中我们不难发现这个函数应该是getDescription,因此本空的答案为virtual string getDescription。
第(3)空需要结合后面各子类才能发现,在Beverage中还应该定义一个函数cost(),而这个函数在Beverage中并没有实现,因此要定义为纯虚函数,所以第(3)空的答案为virtual int cost()=0。
第(4)空在类CondimentDecorator中,且是该类唯一的一条语句,而他的子类分别是奶泡和摩卡,在奶泡和摩卡这两个类中,都用到了Beverage*beverage,而在使用之前并没有说明,因此这就可以说明,Beverage*beverage是在父类CondimentDecorator中定义的,子类直接继承使用,因此第(4)空的答案为Beverage*beverage。
第(5)和第(6)空在主函数当中,其中第(5)空是要创建一个Mocha对象,应该调用的是类Mocha的构造函数,从类Mocha中,我们可以看出,其构造函数Mocha的参数是一个Beverage类型的对象指针,而在主函数中,开始就定义了一个Beverage类型的对象指针beverage,因此这里只需填写beverage即可。同理第(6)空的答案也是beverage。
包含此试题的试卷
你可能感兴趣的试题

-
- A.V(S2)和P(S4)
- B.P(S2)和V(S4)
- C.P(S2)和P(S4)
- D.V(S2)和V(S4)
- 查看答案

-
- A.V(S1)P(S2)和V(S3)
- B.P(S1)V(S2)和V(S3)
- C.V(S1)V(S2)和V(S3)
- D.P(S1)P(S2)和V(S3)
- 查看答案

-
- A.P(S4)和V(S4)V(S5)
- B.V(S5)和P(S4)P(S5)
- C.V(S3)和V(S4)V(S5)
- D.P(S3)和P(S4)V(P5)
- 查看答案

-
- A.P(S3)和V(S4)V(S5)
- B.V(S3)和P(S4)P(S5)
- C.P(S3)和P(S4)P(S5)
- D.V(S3)和V(S4)V(S5)
- 查看答案

-
- A.P(S2)和P(S4)
- B.P(S2)和V(S4)
- C.V(S2)和P(S4)
- D.V(S2)和V(S4)
- 查看答案