Java设计模式 装饰类

来源:互联网 发布:中国反倾销数据统计 编辑:程序博客网 时间:2024/06/03 21:25

装饰类经常出现在Java IO流中,

像BufferReader类就是InputStreamReader类的装饰类,还有很多例子

下面是一个简单的例子来帮助更好的理解 装饰类

package test;//通过SuperPerson装饰Person,增强了eat方法的功能class Person {public void eat() { //吃饭System.out.println("吃饭");}}class SuperPerson {  //装饰类,装饰Person类,强化Person的功能Person p;public SuperPerson(Person p) {this.p = p;}public void eat() { //吃饭System.out.println("开胃菜");System.out.println("喝酒");p.eat();System.out.println("甜点");}}class Test {public static void main(String[] args) {Person p = new Person();SuperPerson sp = new SuperPerson(p);sp.eat();}}


0 0