日期:2010-04-16  浏览次数:20535 次

前阵子的工作涉及一些网络编程,使用了面向流的方式做传输数据。在代码过程中,遇到一个新需求就是要统计流量。其实最简单的办法就时在读写流的地方增加代码,把功能增加上去就可以。但是我觉得那样对我原理的代码框架影响较大,基于尽量不影响原来的代码的考虑,我想到了Decorator设计模式。

先把代码贴出来,在做解释吧:

   

以下为引用的内容:
 public class EventStream : Stream
    {
        public event EventHandler<FStreamDataEventArgs> OnBeforeRead;
        public event EventHandler<FStreamDataEventArgs> OnBeforeWrite;

        private Stream stream;
        public EventStream(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("EventStream");
            this.stream = stream;
        }

        [ ==== Stream members ==== ]#region [ ==== Stream members ==== ]
        public override bool CanRead
        {
            get { return stream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return stream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return stream.CanWrite; }
        }

        public override void Flush()
        {
            stream.Flush();
        }

        public override long Length
        {
            get { return stream.Length; }
        }

        public override long Position
        {
            get
            {
                return stream.Position;
            }
            set
            {
                stream.Position = value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
      &nbs