Common Bits&Bytes Patterns - Iterator Pattern, Part 4 of 5
Continued from http://dotnet.org.za/willy/archive/2008/05/18/common-bits-amp-bytes-patterns-strategy-pattern-part-3-of-5.aspx.
I was recently asked to give an example of where I used the patterns introduced so far, namely the Singleton, the Template Method and the Strategy patterns.
The singleton pattern is probably the most widely used pattern, used typically to initialise and make available an instance of specific state, i.e. configuration state in a class, or to implement a service, which requires one instance, typically pre-loaded and therefore available to service a number of clients. While the singleton pattern is simple with a read-only environment, a singleton that supports modifiable state, requires appropriate synchronisation, thus increasing code complexity.
The Template Method pattern is often used with wizards and code generators, that typically generate base code that the user overrides. I thought long and hard of an instance of the pattern in code I have designed or developed recently ... coming up with a 'null' result set.
The Strategy pattern is a powerful pattern, which I have used a number of times. One of the examples was a security service factory which used the factory pattern (to be covered in the next and final post of this mini-series) allowing subclasses to instantiate .NET based services, based on a common creation interface, using .NET reflection. The strategy pattern allowed me to encapsulate the common security features, making the numerous security service assemblies interchangeable. The final post may include extracts from this service factory to highlight the benefits.
Strategy Pattern
| Category | Behavioural design pattern |
| Intent | Provide access to access elements of a collection sequentially |
| Applicability | Provide a uniform interface for traversing different collections without exposing its internal structures. The iterators are commonly used by operations such as the foreach loop, as shown in the code extract below, obtained from the MSDN library, which implements the IEnumerable interface. |
Class Diagram
Source Code Example (from MSDN)
1: // Declare the collection:
2: public class SampleCollection
3: { 4: public int[] items;
5:
6: public SampleCollection()
7: { 8: items = new int[5] { 5, 4, 7, 9, 3 }; 9: }
10:
11: public System.Collections.IEnumerable BuildCollection()
12: { 13: for (int i = 0; i < items.Length; i++)
14: { 15: yield return items
;
16: }
17: }
18: }
19:
20: class MainClass
21: { 22: static void Main()
23: { 24: SampleCollection col = new SampleCollection();
25:
26: // Display the collection items:
27: System.Console.WriteLine("Values in the collection are:"); 28: foreach (int i in col.BuildCollection())
29: { 30: System.Console.Write(i + " ");
31: }
32: }
33: }
Code Complexity Code Metrics
See you for part 5. ... the Factory pattern.