Discovery of design patterns in the net framework class library we use (3)

Source: Internet
Author: User

 

Iterator Pattern)

Many programming tasks are a set of operations. Whether it is a simple object list or a complex B-Tree set, we need to frequently access the elements in the set. We often use some methods to access the elements in these sets, for example, from front to back, from back to front, or access in ascending or descending order.
One of the most common basic methods is to store the object list in the array, the array type has been built in VB. NET and C # language, they all have a circular structure for listing array elements: in C #, It is Foreach, in VB. NET is For Eeah. Here is an example of an enumerated array:
Int [] values = new int [] {1, 2, 3, 4, 5 };
Foreach (int I in values)
{
Console. Write (I. ToString () + "");
}
These statements use an iterator internally. All you know is that the elements in the array can be enumerated in each loop.
To make these statements run properly, the array object must be IEnumerable in the expression, and all the collection classes that implement the IEnumerable object can be traversed (that is, enumeration). The IEnumerable interface has a method: GetEnumerator, this method returns a type that implements IEnumerator, which enables IEnumerator to enumerate the set. It has a Current attribute, and has methods that can enumerate elements from start to end in the forward collection-MoveNext and Rest. These object collection classes are all System. in the Collections namespace, these collection classes are the same as arrays, And the IEnumerable interface is used to enumerate the elements in the set.
If you look at the language MSIL (Microsoft intermediate language) generated by the C # compiler using the Foreach statement, you will find that most collection classes use enumerators for enumeration. The following example uses IEnumerator for enumeration. It implements the same functions as the previous example:
Int [] values = new int [] {1, 2, 3, 4, 5 };
IEnumerator e = (IEnumerable) values). GetEnumerator ();
While (e. MoveNext ())
{
Console. Write (e. Current. ToString () + "");
}
. NET Framework uses IEnumerable and IEnumerator to apply the iterator mode. The iterator mode allows you to easily traverse a set without displaying the internal processing process. The iteration class that implements IEnumerator is separated from the Collection class that implements IEnumerable. This class is responsible for processing the enumerated State (including how to express the elements in the current array and how to iterate the elements in the set ), and include the enumerated algorithm. This method allows you to enumerate the set iterator using different methods at the same time without adding any complexity to the set!

Decorator Pattern)

Effective executable programs include reading, writing, and writing. Resources are abstracted as byte streams no matter where the Read and Write resources come from ,. NET using System. IO. stream class to express this abstraction. Whether it comes from text files, TCP/IP network communication, or other entities, FileStream and NetworkStrem inherit the Stream class, you can easily process the data regardless of the data source. Below is a method to output the bytes in the stream to the console:

Public static void PrintBytes (Stream s)

{

Int B;

While (B = fs. ReadByte ()> = 0)

{

Console. Write (B + "");

}

}

Reading a byte from a stream at a time is not a very effective method. For example, the hardware can (and most suitable) continuously read data blocks from a disk into a large block, if you know that you want to read some characters, it is better to extract the data block from the disk at one time and process these characters in the memory. In the net Framework, the BufferedStream class is responsible for processing such operations. The BufferedStream class constructor has a parameter that can be any Stream object to be cached. The BufferedStream class reloads many Stream methods, for example, Read and Write provide more powerful functions (this function is actually a buffer, Translator's note ). Since BufferedStream is a subclass of the Stream class, you can use it like other Stream classes. (It is worth noting that FileStream has built-in buffer function)
Similarly, you can use the System. Security. Cryptography. CryptoStream class to freely encrypt and decrypt any stream object. The following example shows how to call my printing method using several different types of stream objects:

MemoryStream MS = new MemoryStream (new byte [] {1, 2, 3, 4, 5, 6, 7, 8 });

PrintBytes (MS );

BufferedStream buff = new BufferedStream (MS );

PrintBytes (buff );

Buff. Close ();

FileStream fs = new FileStream (".../decorator.txt", FileMode. Open );

PrintBytes (fs );

Fs. Close ();

This seamless combination method, the ability to dynamically add functions to objects is an example of the decoration mode. As shown in the following figure:

For each Stream instance, you can package the Stream into a BufferedStream to add a buffer function to the Stream without changing the data interface (that is, the Stream-type interface ), because it is only a combination object (for example, after the FileStream instance is passed as a parameter to the constructor of the BufferedStream instance, this BufferedStream is a FileStream instance with the buffer function, other stream instances can also use this operation to expand their functions. This is the essence of the decoration mode! This method is more elegant than inheriting a specific stream type during compilation (for example, if the inherited method is used, FileStream implements the buffer function, instead, you have to have a subclass that inherits the FileStream class with the buffer function. The biggest problem with this method is that the entire inheritance tree is very bloated. Note ), because the previous method can be implemented at runtime! The core function of the decoration mode is that all the decorators implement an interface or reload an abstract base class (such as Stream abstract base class) and provide extra functions. For example, BufferedStream reloads the Read method to provide the function of reading data from a buffer, rather than directly reading data like other streams. As in the previous example, any composite modifier provides the same functionality as its base class, no matter how complicated it is.

 

 

Note: The Inheritance subclass of System. IO. Stream in Net FrameWork:

System. IO. Stream
System. Data. OracleClient. OracleBFile
System. Data. OracleClient. canclelob

System. IO. BufferedStream

System. IO. FileStream

System. IO. MemoryStream

System. Net. Sockets. NetworkStream

System. Security. Cryptography. CryptoStream

 

BufferedStream and CryptoStream are the decorators in the decorator mode. They provide special functions for other Stream objects.

 



From people who take hobbies as their work

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.