从时序图中可以看到,当我们调用LoggingSignInDecorator对象的SignIn()方法时,因为LoggingSignInDecorator对象的User属性值为SecuritySignInDecorator对象,所以将执行SecuritySignInDecorator对象的SignIn()方法,该方法会先执行IsValid()私有方法,然而再调用User属性对象的SignIn()方法。由于SecuritySignInDecorator的User属性值为User对象,因此执行User对象的SignIn()方法。待SignIn()方法执行完毕,最后再执行LoggingSignInDecorator对象的Logging()方法。
注意上述的时序图,如果在LoggingSignInDecorator对象的SignIn()方法中,Logging()方法放在base.SignIn()前,则应该先执行Logging()方法,然后才是SignIn()方法。
不需要添加新的Decorator对象,通过上述的实现方式,我们就轻易地完成了对User对象SignIn()方法权限控制和日志记录的装饰。
二、.Net Framework中的Decorator模式
在。Net Framework中,有关流的处理就使用了Decorator模式。我们知道,所有的流操作都有一个共同的基类System.IO.Stream,它是一个抽象类,主要包含了Read、Write等行为。而针对文件流和网络流定义的类FileStream和NetworkStream,都继承了Stream类,它们的读写操作的实现自然是不同的。然而,当我们需要提高流读写性能的时候,不管是文件流还是网络流,。Net都提供了同样的方式,即通过Buffer存放流数据以达到性能改进的目的。此时,Buffer的作用对于流的读写操作而言,就相当于一个装饰的作用。同样的,如果我们要求对文件流或网络流的数据读写进行加密操作,以保障数据的安全,那么这个加密的职责同样是一种装饰作用,并且Buffer与加密职责是并行不悖的,有时候也许需要为流操作共同加上这两项职能,这些要求完全符合Decorator模式。
在。Net Framework中,以上的实现可以用类图来表示:

在类图中,BufferedStream和CryptoStream就相当于Decorator类,不过在这里并没有定义抽象的Decorator类,因为它们不需要有共同的逻辑进行抽象。
.Net Framework对于Stream类的定义如下:
public abstract class Stream:MashalByRefObject,IDisposable { static Stream() { Stream.Null = new Stream.NullStream(); } protected Stream() { this._asyncActiveCount = 1; } public abstract int Read([In,Out]byte[] buffer, int offset, int count); public abstract void Write(byte[] buffer, int offset, int count); //…… [NonSerialized] private int _asyncActiveCount; } 注意在BufferedStream和CryptoStream类中是在构造函数中传入要装饰的对象: public sealed class BufferedStream:Stream { public BufferedStream(Stream stream):this(stream,0x1000){} public BufferedStream(Stream stream, int bufferSize) { if (stream == null) { throw new ArgumentNullException("stream"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize", string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_MustBePositive"), new object[] { "bufferSize" })); } this._s = stream; this._bufferSize = bufferSize; if (!this._s.CanRead && !this._s.CanWrite) { __Error.StreamIsClosed(); } } public override int Read([In, Out] byte[] array, int offset, int count) { //…… if (this._s == null) { __Error.StreamIsClosed(); } int num1 = this._readLen - this._readPos; if (num1 == 0) { //处理buffer的操作 num1 = this._s.Read(this._buffer, 0, this._bufferSize); if (num1 == 0) { return 0; } this._readPos = 0; this._readLen = num1; } //…… Buffer.InternalBlockCopy(this._buffer, this._readPos, array, offset, num1); this._readPos += num1; if (num1 < count) { int num2 = this._s.Read(array, offset + num1, count - num1); num1 += num2; this._readPos = 0; this._readLen = 0; } return num1; } //Write与其它方法略 private Stream _s; } |
上一页 [1] [2] [3] [4] [5] 下一页

【责编:John】