装饰模式

 

装饰模式的优点和缺点:

 (1)装饰模式与继承关系的目的都是要扩展对象的功能,但是装饰模式可以提供更多的灵活性。

   (2)通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。

   (3)灵活性是把双刃剑,使用时比继承更容易出错。

 

 

 

 

众所周知很多时候买车都是要加装潢的,也就是所谓的QJ,增加车的功能就非常适用装饰模式,因为装饰模式本身的一大优点就是扩展原有功能。以下环境为JDK1.8,否则static 和 abstract无法同时修饰一个类。

 

public class DecoratorDemo {
  interface Car {
    void operation();
  }

  static class Accord implements Car {

    @Override
    public void operation() {
      System.out.println("自动启停");
      System.out.println("座椅通风");
      System.out.println("座椅位置调节");
    }
  }

  static abstract class AbstractDecoratorAccord implements Car {
    protected Car accord;
  }

  static class DecoratorAccord extends AbstractDecoratorAccord {

    public DecoratorAccord(Car car){
      super.accord = car;
    }
    @Override
    public void operation() {
      if (accord != null) {
        accord.operation();
        System.out.println("HUD抬头显示");
      }
    }
  }

  public static void main(String[] args) {
Car car = new DecoratorAccord(new Accord());
car.operation();

} }

 装饰模式和适配器模式有些相似,但是适配器更多的是进行功能转换,而装饰更多的是扩展功能。

装饰模式中装饰器和组件保持了同一接口,而适配器并不需要。

转载于:https://www.cnblogs.com/sstone/p/8472852.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值