阅读下列说明和C++代码,将应填入(n)处的字句写在答题纸的对应栏内。 【说明】某发票(Invoice)由抬头(Head)部分、正文部分和脚注(Foot)部分构成。现采用装饰(Decorator)模式实现打印发票的功能,得到如图5-1所示的类图。 【C+

admin2017-11-28  9

问题 阅读下列说明和C++代码,将应填入(n)处的字句写在答题纸的对应栏内。
【说明】某发票(Invoice)由抬头(Head)部分、正文部分和脚注(Foot)部分构成。现采用装饰(Decorator)模式实现打印发票的功能,得到如图5-1所示的类图。

【C++代码】
    #include
    using namespace std;
    class Invoice{
    public:
    (1)  {
    cout<<“This is the content of the invoice!”<    }
};
class Decorator:public Invoice{
    Invoice*ticket;
public:
    Decorator(Invoice*t)  {ticket=t;}
    void printInVoice(){
    if(ticket!=NULL)
    (2);
    }
};
class HeadDecorator:public Decorator{
public:
    HeadDecorator(Invoice*t):Decorator(t){  }
    void printInvoice(){
    cout<<“This iS the header of the invoice!”<    (3) ;
    }
};
class FootDecorator:public Decorator{
public:
    FootDecorator(Invoice*t):Decorator(t){)
    void printInvoice(){
    (4) ;
    cout<<“This is the footnote of the invoice!”<    }
};
int main(void)  {
    Invoice t;
    FootDecorator f(&t);
    HeadDecorator h(&f);
    h.print工nVoice();
    cout<<“一一一一一一一一一一一一一一一一一一一”<    FootDecorator a(NULL);
    HeadDecorator b((5));
    b.printInVoice();
    return 0;
}
程序的输出结果为:
This is the header of the invoice!
This  is  the  content of  the  invoice!
This  is  the  footnote of the  invoice!
……………………
This  is  the header of  the  invoice!
This  is  the  footnote of the  invoice!

选项

答案(1)virtual void printlnvoice() (2)ticket一>printlnvoice0 (3)Decorator::printlnvoice() (4)Decorator::printlnvoice() (5)&a

解析 本题考查装饰(Decorator)模式的基本概念和应用。
装饰模式属于结构型设计模式,其设计意图是动态地给一个对象添加一些额外的职责。就增加功能而言,装饰模式比生成子类更加灵活。装饰模式的结构如图5-2所示。

其中:
Component定义一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent定义一个对象,可以给这个对象添加一些职责。
Decorator维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
ConcreteDecorator向组件添加职责。
装饰模式适用于:
在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
处理那些可以撤销的职责。
当不能采用生成子类的方式进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是,由于类定义被隐藏,或类定义不能用于生成子类。
本题将装饰模式用于实现打印发票问题。图5.1的类图中,类Invoice对应图5-2中的Component,其功能是打印发票的内容;HeadDecorator和FootDecorator是两个ConcreteDecorator,向组件中添加打印发票抬头和发票脚注的功能。
方法printlnvoice是Invoice中定义的接口,Component类中应定义一个与之一致的接口。在C++中,父类和子类之间共享接口,通常采用虚拟函数。由此可知,空(1)处应填写“virtual void printlnvoice()”。这个接口在类Decorator、HeadDecorator和FootDecorator中分别进行了重置,分别对应代码中的空(2)~(4)。
类Decorator中保持了一个指向Component对象的指针——ticket,用来接收所要装饰的组件Invoice。因此空(2)处应填写“ticket.>printlnvoice0”。类HeadDecorator和FootDecorator是在打印发票内容的基础上,打印发票的抬头和脚注,所以空(3)、(4)处都应填写“Decorator::printlnvoice0”。
最后一空考查的是装饰模式的调用,由main()函数中给出的第一次调用可以获得一些提示,推断出空(5)出应填写“&a”。
转载请注明原文地址:https://kaotiyun.com/show/CKDZ777K
0

相关试题推荐
随机试题
最新回复(0)