
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Wrapping a String Hash for Ease of Use
|
969
The following code takes a StringReader object (stringReader) that was initialized
with the string and hash produced by the previous code and decorates it with a
StringReaderHash object:
StringReader stringReader = new StringReader(stringWriterHash.ToString( ));
StringReaderHash stringReaderHash = new StringReaderHash( );
stringReaderHash.SetReader(stringReader);
Console.WriteLine("stringReaderHash.ReadToEndHash( ): " +
stringReaderHash.ReadToEndHash( ));
If the original string is modified after the hash is added, the ReadToEndHash method
throws an exception.
Discussion
The decorator design pattern provides the ability to modify individual objects with-
out having to modify or subclass the object’s class. This allows for the creation of
both decorated and undecorated objects. The implementation of a decorator pattern
is sometimes hard to understand at first. An abstract decorator class is created that
inherits from the same base class as the class you will decorate. In the case of this
recipe, you will decorate the
StringReader/StringWriter classes to allow a hash to be
calculated and used. The
StringReader class inherits from TextReader, and the
StringWriter class inherits from TextWriter. Knowing this, you create two abstract
decorator classes: ...