Design Patterns in C#: Kanchan Naik
Design Patterns in C#: Kanchan Naik
Designpatterns.rar
Design Patterns In C#
Design patterns provide general solutions or a exible way to solve common design problems. This
article provides an introduction of design patterns and how design patterns are implemented in C# and
.NET.
Before starting with design patterns in .NET, let's understand what is the meaning of design patterns
and why they are useful in software architecture and programming.
What are Design Patterns in software development?
Design Patterns in the object-oriented world is a reusable solution to common software design
problems that occur repeatedly in real-world application development. It is a template or description of
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 speci c designs to solve their problems. Pattern choice and
usage among various design patterns depends on individual needs and problems. 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 speci c 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 is the
authors of the book, "Design Patterns: Elements of Reusable Object-Oriented Software". These 23
patterns are grouped into three main categories:
C# Corner Login
Design Patterns In CSharp
Creational Design Pattern
1. Factory Method
2. Abstract Factory
3. Builder
4. Prototype
5. Singleton
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 a way that they are separated from their
implementing system. That provides more exibility in deciding which object needs to be created or
instantiated for a given scenario. There are the following ve such patterns.
Abstract Factory
This 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
C# Corner
interface is responsible for creating a set of related objects or dependent objects without specifying Login
their concrete classes.
The UML class diagram below describes an implementation of the abstract factory design pattern.
Design Patterns In .NET
The classes, objects, and interfaces used in the above UML diagram are described below.
1. Client
This class uses the Abstract Factory and Abstract Product interfaces to create 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 product.
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 In .NET
Design Patterns In .NET
In the above abstract factory design pattern, the source code template client has two private elds 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 elds 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 the de nition of a method 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 override the method of
C# Corner Login
the base class to generate a set of related objects required by the client. There can be a speci ed
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 speci c
functionality. Objects of these classes are generated by abstractfactory classes to populate the client.
A 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 rst 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 In .NET
Design Patterns In .NET
AbstractFactory Patterns Form
Design Patterns In .NET
Output
Design Patterns In .NET
The example code above creates two client objects, each passing to a di erent type of factory
constructor. Types of generated objects are accessed through the client's properties.
Note
While studying abstract factory patterns, one question is, what are concrete classes? So I Googled 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.
C# Corner Login
Here is a detailed article on Abstract Factory Design Pattern In C#
Singleton Design Pattern
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 speci c 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 In .NET
In the singleton patterns, the 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 de ned 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, which could lead to subclassing 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 In .NET
Lazy initialization of singleton pattern
Design Patterns In .NET
Thread-safe (Double-checked Locking) initialization of singleton pattern
Design Patterns In .NET
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.
C# Corner Login
A 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 speci c information that is required to be instantiated only once and
held in only one instance.
Class ApplicationState
Design Patterns In .NET
Singleton pattern form
Design Patterns In .NET
Output
Design Patterns In .NET
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.
Here is a detailed article on Abstract Factory Design Pattern In C#
Interview Questions
Going for an interview, here are Interview Questions on Design Patterns.
Summary
I hope this article gives you an introduction to 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 be explained in my next article.
Recommended Articles
Here is a list of some highly recommended articles related to design patterns.
C# Design patterns Abstract Design patterns Factory Design patterns Singleton Design patterns
OUR BOOKS
Kanchan Naik
https://www.c-sharpcorner.com/members/kanchan-naik2
1888 1.3m
Type your comment here and press Enter Key (Minimum 10 characters)
Nice explanation
Dushyant Patel Nov 10, 2019
1848 142 0 0 0 Reply
Nice article
C#Pankaj Patel Sep 13, 2019
Corner 0 0 Login
Reply
95 21.4k 466.2k
Thanks Kanchan
Mohammad Naderi Aug 06, 2019
1927 63 0 1 0 Reply
Good one, But its wrong about double check lock. Idea of double check lock is minimum number of threads
have to wait and that’s only for rst time. As name implies we check whether instance is null twice, that's
before obtain the lock if its not null we return without locking. Lock is accrued only needed (second check
is for that). Here I updated your sample :- public class Singleton { private static Singleton instance = null;
private Singleton() { } private static object lockThis = new object(); public static Singleton GetInstance { get {
if (instance == null) { lock (lockThis) { if (instance == null) instance = new Singleton(); } } return instance; } } }
Eranda Horanagama Mar 19, 2019
928 1.5k 576.5k 2 2 Reply
Thank you, Eranda. Would you like to help us correct this code? What code will your code
replace? Thanks.
Mahesh Chand Mar 27, 2019
Admin 333.4k 183.2m 1
Abstract factory pattern can also be implemented using Interface, then why Abstract came into picture?
Any speci c bene t of having Abstract class instead of Interface.
Snehlata Shaw Dec 01, 2018
1986 4 0 0 3 Reply
Since it is an Abstract class, we will be able to take advantage of inheritance. Write all functions
working on the abstract of the underlying products in the Abstract factory created.
Arish Saseendran Dec 03, 2018
1981 9 0 0
In Object Oriented Programming, abstraction can be implemented with two approaches - either
using Abstract base classes or with interfaces. For all practical purposes, interfaces are "parent
classes" just like Abstract base classes - you can declare a variable of the interface type, and
have it pointed to one of the derivative class instances. Hence, both can be used to implement
Abstract Factory pattern.
Dinesh Muciliath Jayadevan Dec 28, 2020
C# Corner 1988 2 0 Login
0
Nice one..
Sandip G. Patil Dec 01, 2018
908 1.5k 159.8k 0 0 Reply
About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners