A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© nagi 中级黑马   /  2014-9-14 22:51  /  836 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

适用性:

1 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责,

2 处理那些可以撤销的职责

3 当不能采用生成子类的方法进行扩产时。

参与者:

1 Component

定义一个对象接口,可以给这些对象动态添加职责

2 ConcreteComponent

定义一个对象,可以给这个对象添加一些职责

3 Décorator

维持一个指向Compoent对象的指针,并定义了一个与Compoent接口一致接口。

4 ComcreteDecorator

向组件的添加职责



例子:

publicclass Man implements Person {

   @Override

   publicvoid eat() {

      System.out.println("人在吃饭");

   }

}

//interfacePerson

publicinterface Person {

   publicvoid eat();

}



//Decorator

public  abstractclass Decorator implements Person {

   private Person p ;

   publicvoid setP(Person p) {

      this.p = p;

   }

   @Override

   publicvoid eat() {

      p.eat();

   }

}

//ConcreteDescoratorA

publicclass ManDescoratorA extends Decorator {

   @Override

   publicvoid eat() {

      super.eat();

      reEat();

      System.out.println("ManDescoratorA 类");

   }

   privatevoid reEat() {

      System.out.println("再吃一顿!!");

   }

}

//ConcreteDescoratorB

publicclass ManDescoratorB extends Decorator {

   @Override

   publicvoid eat() {

      super.eat();

      System.out.println("============");

      System.out.println("ManDescoratorB 类");

   }

}

//main主函数

publicclass TestDescorator {

   publicstaticvoid main(String[] args) {

      Man man = new Man();

      ManDescoratorA mdA = new ManDescoratorA();

      ManDescoratorB mdB = new ManDescoratorB();

      mdA.setP(man);

      mdB.setP(mdA);

      mdB.eat();

   }

}



运行结果:

人在吃饭

再吃一顿!!

ManDescoratorA类

============

ManDescoratorB类







总结:从以上的代码我们可以发现装饰者模式比继承更加的灵活,避免了继承体系的臃肿,而且降低了类与类之间的耦合度,我们常常看到和使用到的有For 的增强循环、IO包中的ReadLine()方法对read()方法的增强;装饰者类因为已经增强了已有对象,具备的功能和已有的功能一样,只不过提供了增强类的功能,所以装饰者和被装饰者都属于一个类体系中

评分

参与人数 1技术分 +1 收起 理由
陈君 + 1 赞一个!付出会有回报的

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马