zoukankan      html  css  js  c++  java
  • 设计模式之装饰模式(Decorator)详解及代码示例

    一、装饰模式的定义

      装饰(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

    二、装饰模式优缺点

      装饰(Decorator)模式的主要优点有:

    • 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
    • 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。

      其主要缺点是:

      装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。

    三、装饰模式的实现

      通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关系来创建一个包装对象(即装饰对象)来包裹真实对象,并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰模式的目标。下面来分析其基本结构和实现方法。

      装饰模式主要包含以下角色。

    • 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
    • 具体构件(Concrete    Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
    • 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
    • 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

      装饰模式的结构图如图所示:

                

      我们先来看看我们通过继承的方式新增特性这种实现方式,比如本例使用煎饼果子,代码如下:

    /**
     * 煎饼
     */
    public class Battercake {
        protected String getDesc(){
            return "煎饼";
        }
        protected int cost(){
            return 8;
        }
    }
    
    /**
     * 加蛋的煎饼
     */
    public class BattercakeWithEgg extends Battercake {
        @Override
        public String getDesc() {
            return super.getDesc()+" 加一个鸡蛋";
        }
    
        @Override
        public int cost() {
            return super.cost()+1;
        }
    }
    
    /**
     * 加蛋加香肠的煎饼
     */
    public class BattercakeWithEggSausage extends BattercakeWithEgg {
        @Override
        public String getDesc() {
            return super.getDesc()+ " 加一根香肠";
        }
    
        @Override
        public int cost() {
            return super.cost()+2;
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            Battercake battercake = new Battercake();
            System.out.println(battercake.getDesc()+" 销售价格:"+battercake.cost());
    
            Battercake battercakeWithEgg = new BattercakeWithEgg();
            System.out.println(battercakeWithEgg.getDesc()+" 销售价格:"+battercakeWithEgg.cost());
    
            Battercake battercakeWithEggSausage = new BattercakeWithEggSausage();
            System.out.println(battercakeWithEggSausage.getDesc()+" 销售价格:"+battercakeWithEggSausage.cost());
        }
    }

      最后测试结果为:

    煎饼 销售价格:8
    煎饼 加一个鸡蛋 销售价格:9
    煎饼 加一个鸡蛋 加一根香肠 销售价格:11

      虽然我们也实现了扩展类的功能,但是继承的方式耦合度高,并且如果新增会无限增加类,如果修改原有类,对后面的类影响很大,因此如果使用装饰模式,代码如下:

    public class DecoratorPattern
    {
        public static void main(String[] args)
        {
            Component p=new ConcreteComponent();
            p.operation();
            System.out.println("---------------------------------");
            Component d=new ConcreteDecorator(p);
            d.operation();
        }
    }
    //抽象构件角色 interface Component { public void operation(); }
    //具体构件角色 class ConcreteComponent implements Component { public ConcreteComponent() { System.out.println("创建具体构件角色"); } public void operation() { System.out.println("调用具体构件角色的方法operation()"); } }
    //抽象装饰角色 class Decorator implements Component { private Component component; public Decorator(Component component) { this.component=component; } public void operation() { component.operation(); } }
    //具体装饰角色 class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void operation() { super.operation(); addedFunction(); } public void addedFunction() { System.out.println("为具体构件角色增加额外的功能addedFunction()"); } }

    四、装饰模式的应用场景

      前面讲解了关于装饰模式的结构与特点,下面介绍其适用的应用场景,装饰模式通常在以下几种情况使用。

    • 当需要给一个现有类添加附加职责,而又不能采用生成子类的方法进行扩充时。例如,该类被隐藏或者该类是终极类或者采用继承方式会产生大量的子类。
    • 当需要通过对现有的一组基本功能进行排列组合而产生非常多的功能时,采用继承关系很难实现,而采用装饰模式却很好实现。
    • 当对象的功能要求可以动态地添加,也可以再动态地撤销时。

      装饰模式在 Java 语言中的最著名的应用莫过于 Java I/O 标准库的设计了。例如,InputStream 的子类 FilterInputStream,OutputStream 的子类 FilterOutputStream,Reader 的子类 BufferedReader 以及 FilterReader,还有 Writer 的子类 BufferedWriter、FilterWriter 以及 PrintWriter 等,它们都是抽象装饰类。

      下面代码是为 FileReader 增加缓冲区而采用的装饰类 BufferedReader 的例子:

    BufferedReader in=new BufferedReader(new FileReader("filename.txtn));
    String s=in.readLine();

    五、装饰模式扩展

      装饰模式所包含的 4 个角色不是任何时候都要存在的,在有些应用环境下模式是可以简化的,如以下两种情况。

    • 如果只有一个具体构件而没有抽象构件时,可以让抽象装饰继承具体构件,其结构图如图所示:

                    

    •  如果只有一个具体装饰时,可以将抽象装饰和具体装饰合并,其结构图如图所示:

                   

  • 相关阅读:
    雅虎天气API调用
    HttpOperater
    HttpOperater-模拟HTTP操作类
    页面局部加载,适合Ajax Loading场景(Demo整理)
    FTPHelper-封装FTP的相关操作
    使用SOCKET实现TCP/IP协议的通讯
    IIS目录禁止执行权限
    Oracle10g 安装步骤
    SQL Server 2008、SQL Server 2008R2 自动备份数据库
    SQL列转行
  • 原文地址:https://www.cnblogs.com/jing99/p/12602674.html
Copyright © 2011-2022 走看看