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

admin2017-11-28  40

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

[Java代码]
class Invoice{
    public void print工nVoice()  {
    System.out.println(“This is the content of the invoice!”);
    }
  }
  class Decorator extends Invoice{
    protected Invoice ticket;
    publ ic Decorator(Invoice t){
    ticket=t;
    }
    public void print Invoice(){
    if(ticket!=null)
    (1);
    }
  )
  clas s HeadDecorator extends Decorator{
    public HeadDecorator(Invoice t){
    super(t);
    }
    public void printInVoice()  {
    System.out.println(“This is the header of the invoice!”);
    (2);
    }
  }
  class FootDecorator extends Decorator{
    public FootDecorator(Invoice t){
    super(t);
    }
    public void printInVoice()  {
    (3);
    System.out.println(“This is the footnote of the invoice!”);
    }
  }
  class Test{
    public static void main(String[]args){
    Invoice t=new Invoice();
    Invoice ticket;
    ticket= (4);
    ticket.printInvoice();
    System.out.println(“一一一一一一”);
    ticket=    (5)    ;
    ticket.printInvoice();
    }
}
程序的输出结果为:
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 invojce!

选项

答案(1)ticket.printlnvoice() (2)super.printlnvoice() (3)super.printlnvoice() (4)new HeadDecorator(new FootDecorator(t)) (5)new HeadDecorator(new FootDecorator(null))

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

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

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