java装饰模式-2016软件设计师下半年-下午真题

class Invoice{
    public void printInvoice(){
        System.out.println("this is content");
    }
}

class Decorator extends Invoice{
    protected Invoice ticket;
    public Decorator (Invoice t){
        ticket=t;
    }
    public void printInvoice(){
        if(ticket!=null){
            ticket.printInvoice();
        }
    }
}

class HeaderDecorator extends Decorator{
        
    public HeaderDecorator(Invoice t){
        super(t);
    }
    public void printInvoice(){
        System.out.println("this is the header");
        super.printInvoice();
    }
    
}

class FooterDecorator extends Decorator{
    
    public FooterDecorator(Invoice t){
        super(t);
    }
    public void printInvoice(){
        
        super.printInvoice();
        System.out.println("this is the footer");
    }
    
}



public class zhuangshi {
    
    public static void main(String[] args){
        Invoice t =new Invoice();
        Invoice ticket;
        ticket=new FooterDecorator(new HeaderDecorator(t));
        ticket.printInvoice();
        System.out.println("=====================");
        ticket=new FooterDecorator(new HeaderDecorator(new Decorator(null)));
        ticket.printInvoice();
    }

}

结果

《java装饰模式-2016软件设计师下半年-下午真题》

    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000007475228
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注