Design Patterns in .Net

Design patterns provide general solutions or flexible way to solve common design problems. This article provides a simple introduction regarding learning and understanding design patterns.

Before starting with design patters in .Net let's understand what is meant by design patterns and why is it useful in software programming.

What are Design Patterns in software development?

Design Patterns in the object oriented world is reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description for how to solve problems that can be used in many situations.

"A pattern is a recurring solution to a problem in a context."

"Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." - Christopher Alexander, A Pattern Language.

Patterns are used by developers for their specific design to solve their problems. Pattern choice and usage among various design patterns depends on individual need and their problem. Design patterns are a very powerful tool for software developers. It is important to understand design patterns rather than memorizing their classes, methods and properties. It is also important to learn how to apply patterns to specific problems to get the desired result. This will be the required continuous practice for using and applying design patterns in day to day software development. First identify the software design problem then see how to address these problems using design patterns and determine the best suited design problem to solve the problem.

There are 23 design patterns, also known as Gang of Four (GoF) design patterns. The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable Object Oriented Software". These 23 patterns are grouped into three main categories based on their:

Creational Design Pattern

  1. Factory Method
  2. Abstract Factory
  3. Builder
  4. Prototype
  5. Singleton

Structural Design Patterns

  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Façade
  6. Flyweight
  7. Proxy

Behavioral Design Patterns

  1. Chain of Responsibility
  2. Command
  3. Interpreter
  4. Iterator
  5. Mediator
  6. Memento
  7. Observer
  8. State
  9. Strategy
  10. Visitor
  11. Template Method

In this article, we are learning and understanding Creational Design Patterns in detail including UML diagram, template source code and a real-world example in C#.

Creational Design Patterns provide ways to instantiate a single object or group of related objects. These patterns deal with the process of object creation in such way that they are separated from their implementing system. That provides more flexibility in deciding which object needs to be created or instantiated for a given scenario. There are the following five such patterns.

1. Abstract Factory

Creates a set of related objects or dependent objects. The "family" of objects created by the factory is determined at run-time depending on the selection of concrete factory classes.

An abstract factory pattern acts as a super-factory that creates other factories. An abstract factory interface is responsible for creating a set of related objects or dependent objects without specifying their concrete classes.
 
The UML class diagram below describes an implementation of the abstract factory design pattern.

Design-Patterns-1.jpg

The classes,objects and interfaces used in the above UML diagram is described below.

  1. Client

    This class uses the Abstract Factory and Abstract Product interfaces to crreate a family of related objects.
     
  2. Abstract Factory:

    This is an interface that creates abstract products.
     
  3. Abstract Product:

    This is an interface that declares a type of products.
     
  4. Concrete Factory

    This is a class that implements the abstract factory interface to create concrete products.
     
  5. Concrete Product

    This is a class that implements the abstract product interface to create products.

The following code shows the basic template code of the abstract factory design pattern implemented using C#:

Design-Patterns-2.jpg

Design-Patterns-3.jpg 
In the above abstract factory design pattern the source code template client has two private fields that  hold the instances of abstract product classes. These objects will be accessed by inheriting their base class interface. When the client is instantiated, a concrete factory object is passed to its constructor and populate private fields of the client with appropriate data or values.

The Abstractfactory is a base class for concrete factory classes that generate or create a set of related objects. This base class contains a methods definition for each type of object that will be instantiated. The base class is declared as Abstract so that it can be inherited by other concrete factory subclasses.

The concrete factory classes are inheriting from the Abstractfactory class and overrides the method of the base class to generate a set of related objects required by the client. There can be a specifeid number of concrete factory classes depending on the software or application requirements.
Abstractproduct is a base class for the types of objects that the factory class can create. There should be one base type for every distinct type of product required by the client.

The concrete product classes are inheriting from Abstractproduct class. Each class contains specific functionality. Objects of these classes are generated by abstractfactory classes to populate the client.

Real-world example of Abstract factory design pattern using C#

As an example, consider a system that does the packaging and delivery of items for a web-based store. The company delivers two types of products. The first is a standard product that is placed in a box and delivered through the post with a simple label. The second is a delicate item that requires shock-proof packaging and is delivered via a courier.

In this situation, there are two types of objects required, a packaging object and a delivery documentation object. We could use two factories to generate these related objects. The one factory will be responsible for creating packaging and other delivery objects for standard parcels. The second will be responsible for creating packaging and delivery objects for delicate parcels.

Class Client

Design-Patterns-4.jpg

Design-Patterns-5.jpg

AbstractFactory Patterns Form

Design-Patterns-6.jpg

Output

Design-Patterns-7.jpg
 
The example code above creates two client objects, each passing to a different type of factory constructor. Types of generated objects are accessed through the client properties.  

Note

While studying abstract factory patterns, one question is, what are concrete classes? So I Google searched for that and the following is the answer to my question.

A concrete class is nothing but a normal class that has all basic class features, like variables, methods, constructors, and so on.

We can create an instance of the class in other classes.

 2. Singleton

The Singleton design pattern is one of the simplest design patterns. This pattern ensures that the class has only one instance and provides a global point of access to it. The pattern ensures that only one object of a specific class is ever created. All further references to objects of the singleton class refer to the same underlying instance.

There are situations in a project where we want only one instance of the object to be created and shared among the clients. No client can create an instance from outside. It is more appropriate than creating a global variable since this may be copied and leads to multiple access points.

The UML class diagram below describes an implementation of the abstract factory design pattern:

Design-Patterns-8.jpg

In the singleton patterns UML diagram above the "GetInstace" method should be declared as static. This method returns a single instance held in a private "instance" variable.  In the singleton pattern, all the methods and instances are defined as static. The static keyword ensures that only one instance of the object is created and you can call methods of the class without creating an object.

The constructor of a class is marked as private. This prevents any external classes from creating new instances. The class is also sealed to prevent inheritance, that could lead to sub classing that breaks the singleton rules.
 
The following code shows the basic template code of the singleton design pattern implemented using C#.
 
The eager initialization of singleton pattern:

Design-Patterns-9.jpg

Lazy initialization of singleton pattern:

Design-Patterns-10.jpg
 
Thread-safe (Double-checked Locking) initialization of singleton pattern:

Design-Patterns-11.jpg
 
The code above shows the "lockThis" object and the use of locking within the "GetInstance" method. Since  programs can be multithreaded, it is possible that two threads could request the singleton before the instance variable is initialized. By locking the dummy "lockThis" variable, all other threads will be blocked. This means that two threads will not be able to simultaneously create their own copies of the object.
 
Real-world example of Abstract factory design pattern using C#.net :

I am trying to apply this pattern in my application where I want to maintain an application state for user login information and any other specific information that is required to be instantiated only once and held in only one instance.
 
Class ApplicationState :

Design-Patterns-12.jpg

Singleton pattern form:

Design-Patterns-13.jpg

Output

Design-Patterns-14.jpg

The preceding sample code creates two new variables and assigns the return value of the GetState method to each. They are then compared to check that they both contain the same values and a reference to the same object.

I hope this article gives you an introduction about design patterns and various types of design patterns used in .Net.

In this article we learned the Abstract factory and Singleton Design Patterns in detail. The remaining patterns of the Creational Design Pattern Group will explained in my next article.

Up Next
    Ebook Download
    View all
    Learn
    View all