装饰者设计模式

装饰者模式:

概述:动态的给一个类对象添加一些额外的职责,就增加功能来说,Decorator模式相比生成子类更为灵活。
类型:结构型模式

Decortor
+ SetPerson(Person p):void
+eat():void
Person

Man
 +eat():void

ManDecortor A
+eat():void
+ reEat():void

ManDecortor B
+ eat():void

适用性:

1 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责,
2 处理那些可以撤销的职责
3 当不能采用生成子类的方法进行扩产时。

参与者:

1 Component
定义一个对象接口,可以给这些对象动态添加职责
2 ConcreteComponent
定义一个对象,可以给这个对象添加一些职责
3 Décorator
维持一个指向Compoent对象的指针,并定义了一个与Compoent接口一致接口。
4 ComcreteDecorator
向组件的添加职责

例子:

publicclass Manimplements Person {
   @Override
   publicvoid eat() {
      System.out.println("人在吃饭");
   }
}
//interfacePerson
publicinterface Person {
   publicvoid eat();
}

//Decorator
public abstractclass Decoratorimplements Person {
   private Personp ;
   publicvoid setP(Person p) {
      this.p = p;
   }
   @Override
   publicvoid eat() {
      p.eat();
   }
}
//ConcreteDescoratorA
publicclass ManDescoratorAextends Decorator {
   @Override
   publicvoid eat() {
      super.eat();
      reEat();
      System.out.println("ManDescoratorA类");
   }
   privatevoid reEat() {
      System.out.println("再吃一顿!!");
   }
}
//ConcreteDescoratorB
publicclass ManDescoratorBextends 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()方法的增强;装饰者类因为已经增强了已有对象,具备的功能和已有的功能一样,只不过提供了增强类的功能,所以装饰者和被装饰者都属于一个类体系中。
=====================================================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值