Pattern Comparison

There is a symbiosis between patterns and languages, and it is dynamic. As this book has shown, the new features of C# 3.0 have made implementing patterns easier. (A quick comparison of the code in this book with standard C# pattern code will confirm this statement.) Two of the patterns discussed in this chapter—the Prototype and Singleton patterns—raise some interesting points about pattern language features.

Implementing the Prototype pattern was quite a challenge 10 years ago, when obtaining a deep copy of an arbitrary data structure meant creating a graph traversal algorithm from scratch. Now, it can all be done with one method call to Serialize, plus some associated setup of streams. This facility is available to all languages in .NET, and Java has a similar mechanism. Thus, the implementation of the pattern as it was originally envisaged has almost disappeared. Nevertheless, its intent remains, and managing prototypes is still very much part of the developer's task.

Considering the Singleton pattern, is there any way in which the language might help to make it reusable?[7] One solution for achieving reusability is to use C# generics, as shown in Example 5-6.

Example 5-6. Singleton pattern generic code

1 using System; 2 3 // Singleton Pattern Judith Bishop Nov 2007 4 // Generic version 5 6 public class Singleton <T> where T : class, new( ){ 7 Singleton( ) { } 8 9 class SingletonCreator { 10 static SingletonCreator ( ) {} 11 // Private object instantiated ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.