Design Pattern Examples
Overview of object-oriented design patterns
Adapter_Exercise.cs
Go to the documentation of this file.
1
5
6using System;
7
9{
22 internal class Adapter_Exercise
23 {
27 // ! [Using Adapter in C#]
28 public void Run()
29 {
30 Console.WriteLine();
31 Console.WriteLine("Adapter Exercise");
32 try
33 {
34 // Will call Dispose() automatically when exiting the using block
35 using (var dataReaderWriter = new DataReaderWriter(DataReaderWriter.MemoryBlockNumber.Memory_Block_0))
36 {
37 uint memoryBlockSize = dataReaderWriter.MemoryBlockByteSize;
38 byte[] readData = dataReaderWriter.Read(0, memoryBlockSize);
39 string dataDump = dataReaderWriter.BufferToString(readData, memoryBlockSize, 2);
40 Console.WriteLine(" Initial memory block contents:{0}{1}", Environment.NewLine, dataDump);
41
42 // Create the data to be written
43 uint dataSize = 16;
44 int byteOffset = 41;
45 byte[] writeData = new byte[dataSize];
46 for (int index = 0; index < dataSize; ++index)
47 {
48 writeData[index] = (byte)(index + 1);
49 }
50
51 // Display the data to be written
52 dataDump = dataReaderWriter.BufferToString(writeData, dataSize, 2);
53 Console.WriteLine(" Data to be written to memory block:{0}{1}", Environment.NewLine, dataDump);
54
55 Console.WriteLine(" Writing data to byte offset {0}...", byteOffset);
56 // Write the data to the external component
57 dataReaderWriter.Write(byteOffset, writeData, dataSize);
58
59 Console.WriteLine(" Reading back the memory block...");
60 // Read the data from the external component
61 readData = dataReaderWriter.Read(0, memoryBlockSize);
62 Console.WriteLine();
63
64 // Display the data read back. Should be the same as was written.
65 dataDump = dataReaderWriter.BufferToString(readData, memoryBlockSize, 2);
66 Console.WriteLine(" Current memory block contents:{0}{1}", Environment.NewLine, dataDump);
67 }
68
69 }
71 {
72 Console.WriteLine("Error with startup or shutdown! {0}", e.Message);
73 }
75 {
76 Console.WriteLine("Error with reading or writing! {0}", e.Message);
77 }
78 Console.WriteLine(" Done.");
79 }
80 // ! [Using Adapter in C#]
81 }
82}
Example of using the Adapter Pattern in C#.
void Run()
Executes the example for the Adapter Pattern in C#.
Represents an error that occurred when reading or writing data in the Data reader/writer.
Represents a data reader/writer to a caller.
MemoryBlockNumber
Represents the memory blocks that can be accessed. Hides how memory blocks are actually identified.
Represents an error that occurred during initialization or shut down of the Data reader/writer.
The namespace containing all Design Pattern Examples implemented in C#.