日期:2014-05-20  浏览次数:20769 次

还请大家帮忙!关于java构造函数的一个小问题
在下面的Java程序代码中,类SalesTicket能够完成打印票据正文的功能,类HeadDecorator与FootDecorator分别完成打印票据的台头和脚注的功能。   已知该程序运行后的输出结果如下所示,
  这是票据的台头!
  这是票据正文!
  这是票据的脚注!
------------------------
  这是票据的台头!
  这是票据的脚注!
[Java   程序代码]
  public   class   SalesTicket  
{  
public   void   printTicket()  
{  
System.out.println( "这是票据正文! ");  
}  
}  
public   class   Decorator   extends   SalesTicket
{
  SalesTicket   ticket;  
public   Decorator(SalesTicket   t){   ticket   =   t;  
}  
public   void   printTicket()
{   if(ticket   !=   null)  
ticket.printTicket();  
}  
}   public   class   HeadDecorator   extends   Decorator
{  
public   HeadDecorator(SalesTicket   t)   {
super(t)   ;  
}  
public   void   printTicket()  
{  
System.out.println( "这是票据的台头! ");
super.printTicket();
}
public   class   FootDecorator   extends   Decorator
{  
public   FootDecorator(SalesTicket   t)  
{
  super(t)   ;
  }
  public   void   printTicket()   {  
super.printTicket();
System.out.println( "这是票据的脚注! ");  
}   }  
public   class   Main  
{   public   static   void   main(String[]   args)
  {  
T   =   new   HeadDecorator(   new   FootDecorator(new   SalesTicket())   );  
T.   printTicket()   ;  
System.out.println( "------------------------ ");
T=new   FootDecorator(new   HeadDecorator   (null));
T.printTicket();
}
}
我请问一下这个程序为啥会输出上面的结果,还有T   =   new   HeadDecorator(   new   FootDecorator(new   SalesTicket())   );   这条语句是何意?
请高手指点

------解决方案--------------------
T = new HeadDecorator( new FootDecorator(new SalesTicket()) );
相当与这样:
SalesTicket st = new SalesTicket();
FootDecorator fd = new FootDecorator(st);
HeadDecorator hd = new HeadDecorator(fd);
t = hd;
按照这个步骤以此执行即可。