Sunday, July 31, 2011

Examples of Design Patterns used in .Net Framework, Enterprise Library etc.

Design Pattern concepts can sometimes be overwhelming and leave junior developers wondering as to where there concepts can be put to use. The various UML notations and the Gang of Four definitions for each of the design patterns make it look very difficult to understand in practical terms.


Fortunately, most of the design patterns are already being used in .Net Framework, Enterprise Library and so on. So to make it easier to understand, I have tried to find such examples for most of the Gang of Four design patterns below.


All the material below has been found from other websites and blogs - I have also provided their links wherever necessary.



Creational Patterns

Factory Pattern (Abstract Factory pattern and Factory Method):

The Abstract Factory pattern is essentially a generalization of the Factory Method as it creates families of related classes that interact with each other in predictable ways.
Over time the differences these two factory patterns have become blurry and developers usually just mention the Factory pattern, meaning a class that manufactures objects that share a common interface or base class.

Usage of Factory pattern in .Net Framework: The Factory Method is frequently used in .NET. One example is the System.Convert class which exposes many static methods that, given an instance of a type, returns another new type. Convert.ToBoolean accepts a string and returns a boolean with value true or false depending on the string value.

Usage of Factory pattern in Enterprise Library: This pattern is extensively used in the Unity block of Enterprise Library. With Unity Container, different types of objects can be instantiated by just making changes to unity configuration files.



Singleton Pattern:

Implementation example of Singleton class in .Net:


The.NET Framework uses the Singleton pattern with .NET Remoting when it launches server-activated objects. One of the activation modes of server objects is called Singleton and their behavior is in line with the GoF pattern definition, meaning that there is never more than one instance at any one time.

Difference between Singleton class and Static class:


Prototype Pattern:
The implementation of the Prototype pattern in C# is greatly assisted by two facilities in the .NET Framework: cloning and serialization. Both of these are provided as interfaces in the System namespace.
The Prototype pattern co-opts one instance of a class and uses it as a "breeder" for all future instances. Prototypes are useful when object initialization is expensive and you anticipate few variations on the initialization parameters. In this context, the Prototype pattern can avoid expensive "creation from scratch," supporting cheap cloning of a pre-initialized prototype. However, cloning via serialization is not particularly cheap itself, so it is worth considering shallow cloning if you are absolutely sure you have a flat, single-level data structure.

More in the below link:


Builder Pattern:
Not very widely used. Still, below is an implementation example:


Structural Patterns

Adapter Pattern:

From .NET-based code you can easily call legacy COM objects and vice versa. In order to use a COM component in your project, all you have to do is add a reference to it via the Add Reference dialog in Visual Studio .NET. Behind the scenes, Visual Studio® .NET invokes the tlbimp.exe tool to create a Runtime Callable Wrapper (RCW) class, contained in an interop assembly. Once the reference has been added (and the interop assembly has been generated for you), the COM component can be used like any other class in managed code. If you were looking at code someone else had written without seeing the list of references (and without examining metadata associated with the classes or their implementation), you would be unable to tell which classes were written in a .NET-targeted language and which were COM components.


Bridge Pattern:

This pattern is used to separate an object’s interface from its implementation.
If you build an application that uses a driver to communicate with a database, like with ODBC, you’re using the Bridge pattern. ODBC is a standard API for executing SQL statements and represents the interface.
These Bridge design pattern classes are those that implement the API of the ODBC drivers. The ODBC architecture decouples an abstraction from its implementation so that the two can vary independently for the different database.

Composite Pattern:

When dealing with collections of objects, there are often operations that are appropriate for both a single object and the entire collection. Think about an ASP.NET control. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.
When each item in the collection might itself contain collections of other objects, the use of the Composite pattern is appropriate. Composite is an easy way to represent tree-like collections without having to treat parent and leaf nodes differently.


Decorator pattern:
This pattern is used to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.

Below are some examples that I found to be easier to appreciate.


Unity dependency injection container

Proxy Pattern:

In .NET the Proxy pattern manifests itself in .NET Remoting infrastructure. Whenever an object requires access to an object in a different address space (app domain, process, or machine) a proxy is created that sends the request to the remote object and any data it might need.
Generally with proxies, the client is frequently not even aware that a proxy is at work. Clients applications use proxies to contact Web Services and WCF services which are auto-generated proxy objects.

Façade pattern:
Most of us would have already used this pattern in our applications.


Behavioral Patterns

Observer Pattern

Event-Delegate is something that most of us would have used. Event acts as the Subject and Delegate acts as the Observer.

The Windows Forms Button control exposes a Click event which gets raised whenever the button is clicked. Any class designed to react to this event just needs to register a delegate with that event. The Button class doesn't depend on any of the potential Observers, and each Observer only needs to know the correct type of the delegate for the event (EventHandler, in this case). Since EventHandler is a delegate type and not an interface, each Observer doesn't need to implement an extra interface. Assuming it already contains a method with a compatible signature, it only needs to register that method with the event of the Subject. Through delegates and events, the Observer pattern lets you decouple Subjects and their Observers.

Iterator Pattern:

One of the most basic ways to store a list of objects is in an array. Array types are built into both Visual Basic .NET and C#. Both languages also have a loop structure that aids in iterating over arrays: foreach in C# and For Each in Visual Basic .NET
The object referenced in the In expression must implement IEnumerable. Any collection of objects that implements the IEnumerable interface can be traversed (enumerated). This interface has a single method, GetEnumerator, that returns an object which implements IEnumerator. The IEnumerator class contains the code necessary to iterate through the collection.

Chain of responsibility pattern:

Below is an example of Chain of responsibility pattern using Unity Dependency Injection Container.


Strategy Pattern:

Below are examples of strategy pattern that many of us may have used:


Template Method:

Below is the best example that I could find:


References: