`
vvggsky
  • 浏览: 66883 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Decorator模式

阅读更多
abstract class Component{
 abstract public void printTicket();
}
class SalesTicket extends Component{
 public void printTicket() {
  System.out.println("打印出salesTicket的内容");
 }
}
abstract class TicketDecorator extends Component{
 private Component myTrailer;
 public TicketDecorator(Component myComponent){
  myTrailer=myComponent;
 }
 public void callTrailer(){
  if(myTrailer!=null)
   myTrailer.printTicket();
 }
}
class Header extends TicketDecorator{
 public Header(Component myComponent){
  super(myComponent);
 }
 public void printTicket(){
  System.out.println("打印salesTicket的头信息");
  super.callTrailer();
  
 }
}
class Footer extends TicketDecorator{
 public Footer(Component myComponent){
  super(myComponent);
 }
 public void printTicket(){
  super.callTrailer();
  System.out.println("打印salesTicket的页脚信息");
 }
}
public class Client {

 public static void main(String[] args) {
  System.out.println("====================================");
  new Header(new Footer(new SalesTicket())).printTicket();
  System.out.println("====================================");
  new Footer(new Header(new SalesTicket())).printTicket();
  System.out.println("====================================");
 }

}
输出结果如下:
====================================
打印salesTicket的头信息
打印出salesTicket的内容
打印salesTicket的页脚信息
====================================
打印salesTicket的头信息
打印出salesTicket的内容
打印salesTicket的页脚信息
====================================
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics