CREATIONAL DESIGN PATTERNS
creational design patterns provide various object creation
mechanisms, which increase flexibility and reuse of existing code.
Let's you ensure that a class has only one instance, while
SINGLETON providing a global access.
Let’s you construct complex objects step by step. The pattern
BUILDER allows you to produce different types and representations of an
object using the same construction code.
ABSTRACT FACTORY Let’s you produce families of related objects without
specifying their concrete classes.
Provides an interface for creating objects in a superclass
FACTORY METHOD but allows subclasses to alter the type of objects that
will be created.
Let’s you copy existing objects without making your code
PROTOTYPE dependent on their classes.
@salikhafeez
SINGLETON DESIGN PATTERN
A singleton is a design pattern that restricts the
instantiation of a class to one object. This is useful
when exactly one object is needed to coordinate
actions across the system.
@salikhafeez
COMPARISON
Singleton Class Normal Class
Object
A
Class
Single
Class
Object
Object Object
B C
@salikhafeez
NAÏVE CODE (EXAMPLE)
Common characteristics of
singleton pattern design.
1. Sealed class.
2. Private and parameter less
single constructor.
3. Static variable to hold a
reference to the single created
instance.
4. A public and static way of
getting the reference to the
created instance
@salikhafeez
THREAD-SAFE (EXAMPLE)
Thread Safe approach:
1. The adjacent code is thread-safe.
2. In the code, the thread is locked
on a shared object and checks
whether an instance has been
created or not.
3. The biggest problem with this is
performance; performance
suffers since a lock is required
every time an instance is
requested.
@salikhafeez
USING .NET 4'S LAZY<T> TYPE
Lazy<T> type approach:
1. Instance creation - var singleInstance = AddSingleton<class>.GetInstance;
2. Performant & generic approach to create a single instance of a class.
3. Next, will be using this AddSingleton<T> class for a practical example.
@salikhafeez
WHY NEED
SINGLETON?
Let's take a ServiceProvider
class :
1. This class contains a list of
servers, each server gets added
into the list when an object is
created.
2. Method GetNextServiceProvide()
provides next server's name.
Once it reaches to the last
member of the list, it will start
from the first element in the list.
3. Next, will use AddSingleton<T>
class to create single instance of
ServiceProvider class.
@salikhafeez
WHY NEED SINGLETON?
Singleton<T> Instance New Keyword Instance
Output: Output:
singleInstance1 == singleInstance2 differentInstance1 != differentInstance2
SINGLETON PATTERN, ENSURE THAT A CLASS HAS ONLY
ONE INSTANCE, WHILE PROVIDING A GLOBAL ACCESS.
@salikhafeez
HOPE IT WAS HELPFUL
https://www.linkedin.com/in/salikhafeez/
THANK YOU!
@salikhafeez