Introduction
Design patterns provide general solutions or flexible way to solve common design problems. This article gives you 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 it is useful in software programming?
What are Design Patterns in Software Programming?
Design Patterns in object oriented world is reusable solution to common software design problems which occur again and again in real world application development. It is a template or description for how to solve a problem which can be used in many different situations.
"A pattern is a recurring solution to a problem in a context."
"Each pattern describes a problem which 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 to their particular design to solve their problems. Patterns usage and choice to choose among different design patterns is based on individual need and their problem.
Design patterns are the most powerful tool for software developer. It is important to understand design patterns rather than memorizing its classes, methods and properties. It is also important to learn how to apply pattern to specific problem to get the desired result. This will be required continuous practice of 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 find out the best suited design problem to solve the problem.
There are 23 design patterns also known as Gang of four design patterns (GoF). 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
- Factory Method
- Abstract Factory
- Builder
- Prototype
- Singleton
- Structural Design Patterns
- Adapter
- Bridge
- Composite
- Decorator
- Façade
- Flyweight
- Proxy
- Behavioral Design Patterns
- Chain of Responsibility
- Command
- Interpreter
- Iterator
- Mediator
- Memento
- Observer
- State
- Strategy
- Visitor
- Template Method
In this article, we are learning and understanding Creational Design patterns in detail including UML diagram, template source code and real world example C#*.
Creational Design patterns provide a way to instantiate single object or group of related objects. These patterns deal with the process of object creation in such a way that they are separated from their implementing system. This way, it provides more flexibility in deciding which object needs to be created or instantiated for a given scenario. There are five such patterns:
1) Abstract Factory
It is used to create a set of related objects or dependent objects. The “family” of objects created by factory is determined at run-time according to the selection of concrete factory class.
Abstract factory pattern acts as super factory which creates other factories. In 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:
The classes,objects and interfaces used in the above UML diagram is described below:
- Client: This class is used Abstract Factory and Abstract Product interfaces to create family of related objects.
- Abstract Factory: This is an interface which is used to create abstract products.
- Abstract Product: This is an interface which is used to declare type of products.
- Concrete Factory: This is a class which implements the abstract factory interface to create concrete products.
- Concrete Product: This is a class which 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#.NET:
In the above abstract factory design pattern 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 a client is instantiated, a concrete factory object is passed to its constructor and populate private
fields of client with appropriate data or value.
The
Abstractfactory
is base class to concrete factory classes which generate or create set of related objects. This base class contains 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
Abstractfactory
class and override the method of base class to generate a set of related objects required by client. There can be n number of concrete factory classes depending on software or application requirement.Abstractproduct
is the base class for the types of objects that factory class can create. There should be one base type for every distinct types of product required by 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 client.Real World Example of Abstract Factory Design Pattern using C#.NET
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 shockproof 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
AbstractFactory Patterns Form
OUTPUT
In the above example, code creates two client objects, each passing to different type of factory constructor. Types of generated objects are accessed through the client properties.
Note
While studying abstract factory pattern, one question comes in my mind, i.e., what are concrete classes? So I Google searched the same and below is the answer to my question.
Concrete class is nothing but normal class, which is having all basic class features, like variables, methods, constructors, etc.
We can create an instance of the class in the other classes.
2) Singleton
Singleton design pattern is one of simplest design patterns. This pattern ensures that class has only one instance and provides global point of accessing it. The pattern ensures that only one object of a particular 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 between the clients. No client can create an instance from outside. It is more appropriate than creating a global variable as this may be copied and leading to multiple access points.
The UML class diagram below describes an implementation of the abstract factory design pattern:
In the above singleton patterns UML diagram “
GetInstance
” method should be declared as static
. This method returns single instance held in private
“instance
” variable. In singleton pattern, define all the methods and instance as static
. The static
keyword ensures that only one instance of object is created and you can call methods of class without creating object.
The constructor of class is marked as
private
. This prevents any external classes from creating new instances. The class is also sealed to prevent inheritance, which 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#.NET:
The eager initialization of singleton pattern is as follows:
Lazy initialization of singleton pattern:
Thread-safe (Double-checked Locking) initialization of singleton pattern:
In the above code "
lockThis
" object and the use of locking within the "GetInstance
" method. As 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 application state for user login information and any other specific information which is required to be instantiated only once and held only one instance.
Class ApplicationState
Singleton Pattern Form
OUTPUT
The above 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 will give you an introduction about design patterns and different types of design patterns used in .NET. In this article, we learned Abstract factory and Singleton design pattern in detail. Remaining patterns of creational design pattern group will be explained to you in my next article.