本文主要是介绍设计模式-结构型-装饰器模式-decorator,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
发票基本类
public class Invoice {public void printInvoice() {System.out.println("打印发票正文");}
}
发票正文类
public class Decorator extends Invoice {protected Invoice ticket;public Decorator(Invoice ticket) {this.ticket = ticket;}@Overridepublic void printInvoice() {if (ticket != null) {ticket.printInvoice();}}
}
发票头部类
public class HeadDecorator extends Decorator {public HeadDecorator(Invoice ticket) {super(ticket);}@Overridepublic void printInvoice() {System.out.println("打印发票头");super.printInvoice();}
}
发票尾部类
public class FootDecorator extends Decorator {public FootDecorator(Invoice ticket) {super(ticket);}@Overridepublic void printInvoice() {super.printInvoice();System.out.println("打印发票尾");}
}
演示类
public class Demo {public static void main(String[] args) {Invoice t= new Invoice();Decorator ticket;ticket=new FootDecorator(new HeadDecorator(t));ticket.printInvoice();}
}
演示结果
这篇关于设计模式-结构型-装饰器模式-decorator的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!