• 设计模式--装饰模式


    装饰模式(Decorator),动态的给一个对象条件一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活

    1 public abstract class Component {
    2     public abstract void operation();
    3 }
    1 public class ConcreteComponent extends Component {
    2     @Override
    3     public void operation() {
    4         System.out.println("具体的操作!");
    5     }
    6 }
     1 public abstract class Decorator extends Component {
     2     protected Component component;
     3     public void setComponent(Component component) {
     4         this.component = component;
     5     }
     6     @Override
     7     public void operation() {
     8         if (component != null) {
     9             component.operation();
    10         }
    11     }
    12 }
    1 public class ConcreteDecoratorA extends Decorator {
    2     private String addedState;//本类独有功能
    3     @Override
    4     public void operation() {
    5         super.operation();
    6         addedState = "new State";
    7         System.out.println("具体装饰对象A的操作!");
    8     }
    9 }
     1 public class ConcreteDecoratorB extends Decorator {
     2     @Override
     3     public void operation() {
     4         super.operation();
     5         addedBehavior();
     6         System.out.println("具体装饰对象B的操作!");
     7     }
     8     private void addedBehavior() {
     9         
    10     }
    11 }
     1 public class DecoratorDemo {
     2     public static void main(String[] args) {
     3         ConcreteComponent c = new ConcreteComponent();
     4         ConcreteDecoratorA d1 = new ConcreteDecoratorA();
     5         ConcreteDecoratorB d2 = new ConcreteDecoratorB();
     6         
     7         d1.setComponent(c);
     8         d2.setComponent(d1);
     9         d2.operation();
    10     }
    11 }

    -----以下内容为转载 http://www.cnblogs.com/java-my-life/archive/2012/04/20/2455726.html  这篇文章对装饰模式做出了很好地诠释

    装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。

     在装饰模式中的角色有:

      ●  抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

      ●  具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。

      ●  装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

      ●  具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。

    装饰模式的优点

      (1)装饰模式与继承关系的目的都是要扩展对象的功能,但是装饰模式可以提供比继承更多的灵活性。装饰模式允许系统动态决定“贴上”一个需要的“装饰”,或者除掉一个不需要的“装饰”。继承关系则不同,继承关系是静态的,它在系统运行前就决定了。

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

    装饰模式的缺点

      由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使设计比较易于进行。但是,在另一方面,使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。


    设计模式在JAVA I/O库中的应用

      装饰模式在Java语言中的最著名的应用莫过于Java I/O标准库的设计了。

      由于Java I/O库需要很多性能的各种组合,如果这些性能都是用继承的方法实现的,那么每一种组合都需要一个类,这样就会造成大量性能重复的类出现。而如果采用装饰 模式,那么类的数目就会大大减少,性能的重复也可以减至最少。因此装饰模式是Java I/O库的基本模式。

      Java I/O库的对象结构图如下,由于Java I/O的对象众多,因此只画出InputStream的部分。

      根据上图可以看出:

      ●  抽象构件(Component)角色:由InputStream扮演。这是一个抽象类,为各种子类型提供统一的接口。

      ●  具体构件(ConcreteComponent)角色:由ByteArrayInputStream、FileInputStream、PipedInputStream、StringBufferInputStream等类扮演。它们实现了抽象构件角色所规定的接口。

      ●  抽象装饰(Decorator)角色:由FilterInputStream扮演。它实现了InputStream所规定的接口。

      ●  具体装饰(ConcreteDecorator)角色:由几个类扮演,分别是BufferedInputStream、DataInputStream以及两个不常用到的类LineNumberInputStream、PushbackInputStream。

     半透明的装饰模式

      装饰模式和适配器模式都是“包装模式(Wrapper Pattern)”,它们都是通过封装其他对象达到设计的目的的,但是它们的形态有很大区别。

      理想的装饰模式在对被装饰对象进行功能增强的同时,要求具体构件角色、装饰角色的接口与抽象构件角色的接口完全一致。而适配器模式则不然,一般而言,适配器模式并不要求对源对象的功能进行增强,但是会改变源对象的接口,以便和目标接口相符合。

      装饰模式有透明和半透明两种,这两种的区别就在于装饰角色的接口与抽象构件角色的接口是否完全一致。透明的装饰模式也就是理想的装饰模式,要求 具体构件角色、装饰角色的接口与抽象构件角色的接口完全一致。相反,如果装饰角色的接口与抽象构件角色接口不一致,也就是说装饰角色的接口比抽象构件角色 的接口宽的话,装饰角色实际上已经成了一个适配器角色,这种装饰模式也是可以接受的,称为“半透明”的装饰模式,如下图所示。

      在适配器模式里面,适配器类的接口通常会与目标类的接口重叠,但往往并不完全相同。换言之,适配器类的接口会比被装饰的目标类接口宽。

      显然,半透明的装饰模式实际上就是处于适配器模式与装饰模式之间的灰色地带。如果将装饰模式与适配器模式合并成为一个“包装模式”的话,那么半透明的装饰模式倒可以成为这种合并后的“包装模式”的代表。

    InputStream类型中的装饰模式

      InputStream类型中的装饰模式是半透明的。为了说明这一点,不妨看一看作装饰模式的抽象构件角色的InputStream的源代码。这个抽象类声明了九个方法,并给出了其中八个的实现,另外一个是抽象方法,需要由子类实现。

    复制代码
    public abstract class InputStream implements Closeable {
    
        public abstract int read() throws IOException;
    
     
        public int read(byte b[]) throws IOException {}
    
        public int read(byte b[], int off, int len) throws IOException {}
    
        public long skip(long n) throws IOException {}
    
        public int available() throws IOException {}
        
        public void close() throws IOException {}
        
        public synchronized void mark(int readlimit) {}
        
        public synchronized void reset() throws IOException {}
    
        public boolean markSupported() {}
    
    }
    复制代码

      

      下面是作为装饰模式的抽象装饰角色FilterInputStream类的源代码。可以看出,FilterInputStream的接口与InputStream的接口是完全一致的。也就是说,直到这一步,还是与装饰模式相符合的。

    复制代码
    public class FilterInputStream extends InputStream {
        protected FilterInputStream(InputStream in) {}
        
        public int read() throws IOException {}
    
        public int read(byte b[]) throws IOException {}
        
        public int read(byte b[], int off, int len) throws IOException {}
    
        public long skip(long n) throws IOException {}
    
        public int available() throws IOException {}
    
        public void close() throws IOException {}
    
        public synchronized void mark(int readlimit) {}
    
        public synchronized void reset() throws IOException {}
    
        public boolean markSupported() {}
    }
    复制代码

      

      下面是具体装饰角色PushbackInputStream的源代码。

    复制代码
    public class PushbackInputStream extends FilterInputStream {
        private void ensureOpen() throws IOException {}
        
        public PushbackInputStream(InputStream in, int size) {}
    
        public PushbackInputStream(InputStream in) {}
    
        public int read() throws IOException {}
    
        public int read(byte[] b, int off, int len) throws IOException {}
    
        public void unread(int b) throws IOException {}
    
        public void unread(byte[] b, int off, int len) throws IOException {}
    
        public void unread(byte[] b) throws IOException {}
    
        public int available() throws IOException {}
    
        public long skip(long n) throws IOException {}
    
        public boolean markSupported() {}
    
        public synchronized void mark(int readlimit) {}
     
        public synchronized void reset() throws IOException {}
    
        public synchronized void close() throws IOException {}
    }
    复制代码

       查看源码,你会发现,这个装饰类提供了额外的方法unread(),这就意味着PushbackInputStream是一个半透明的装饰 类。换言 之,它破坏了理想的装饰模式的要求。如果客户端持有一个类型为InputStream对象的引用in的话,那么如果in的真实类型是 PushbackInputStream的话,只要客户端不需要使用unread()方法,那么客户端一般没有问题。但是如果客户端必须使用这个方法,就 必须进行向下类型转换。将in的类型转换成为PushbackInputStream之后才可能调用这个方法。但是,这个类型转换意味着客户端必须知道它 拿到的引用是指向一个类型为PushbackInputStream的对象。这就破坏了使用装饰模式的原始用意。

      现实世界与理论总归是有一段差距的。纯粹的装饰模式在真实的系统中很难找到。一般所遇到的,都是这种半透明的装饰模式。


      下面是使用I/O流读取文件内容的简单操作示例。

    复制代码
    public class IOTest {
    
        public static void main(String[] args) throws IOException {
            // 流式读取文件
            DataInputStream dis = null;
            try{
                dis = new DataInputStream(
                        new BufferedInputStream(
                                new FileInputStream("test.txt")
                        )
                );
                //读取文件内容
                byte[] bs = new byte[dis.available()];
                dis.read(bs);
                String content = new String(bs);
                System.out.println(content);
            }finally{
                dis.close();
            }
        }
    
    }
    复制代码

      观察上面的代码,会发现最里层是一个FileInputStream对象,然后把它传递给一个BufferedInputStream对象,经 过BufferedInputStream处理,再把处理后的对象传递给了DataInputStream对象进行处理,这个过程其实就是装饰器的组装过 程,FileInputStream对象相当于原始的被装饰的对象,而BufferedInputStream对象和DataInputStream对象 则相当于装饰器。

  • 相关阅读:
    ADO.NET
    VS调SQL中存储过程实现登陆
    摇奖
    面向对象、类、字段、属性、构造函数、析构函数
    打架
    2012/7/26Extjs笔记_Ext.grid.EditorGridPanel
    2012/7/30sql2005学习笔记
    SVN版本冲突解决办法(非加锁)
    2012/7/30sqlserver2005学习随笔
    struts环境搭建
  • 原文地址:https://www.cnblogs.com/sun-space/p/5808035.html
Copyright © 2020-2023  润新知