Singleton Design Pattern
- Ensure a class
has only one instance, and provide a global point of access to it.
- Encapsulated
"just-in-time initialization" or "initialization on first
use".
Application needs one, and only one,
instance of an object. Additionally, lazy initialization and global access are
necessary.
The Singleton pattern ensures that a
class has only one instance and provides a global point of access to that
instance.
SingleObject class provides a static method to get its static instance to
outside world.SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObjectobject.

Singlton Exp. -
public class Singleton
{
protected
static Singleton
_obj;
private
Singleton()
{
}
public static Singleton
GetObject()
{
if
(_obj == null)
{
_obj = new
Singleton();
}
return
_obj;
}
public string Print(string
s)
{
return
"Hello " + s;
}
}
Call Singlton Exp : -
protected void BtnShow_Click(object
sender, EventArgs e)
{
Singleton
obj = Singleton.GetObject();
Label1.Text= obj.Print("abc");
//Singleton
obj1 = Singleton.GetObject();
//Label1.Text
= obj1.Print("abc1");
}
Factory Design Pattern :
Factory
pattern deals with the instantiation of object without exposing the
instantiation logic. In other words, a Factory is actually a creator of object
which has common interface.
//Empty
vocabulary of Actual object
public interface IPeople
{
string GetName();
}
public class Villagers : IPeople
{
#region IPeople Members
public string GetName()
{
return "Village Guy";
}
#endregion
}
public class CityPeople : IPeople
{
#region IPeople Members
public string GetName()
{
return "City Guy";
}
#endregion
}
public enum PeopleType
{
RURAL,
URBAN
}
/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{
public IPeople GetPeople(PeopleType type)
{
IPeople people = null;
switch (type)
{
case PeopleType.RURAL:
people = new Villagers();
break;
case PeopleType.URBAN:
people = new CityPeople();
break;
default:
break;
}
return people;
}
}
In
the above code you can see I have created one interface called IPeople and implemented two classes from it as Villagers and CityPeople. Based on the type passed into the factory
object, I am sending back the original concrete object as the Interface
IPeople.
Dependency Inversion
Principle (DIP)
The Dependency Inversion Principle states
that:
- High level modules should not
depend upon low level modules. Both should depend upon abstractions.
- Abstractions should not depend
upon details. Details should depend upon abstractions.
It helps us to develop loosely couple code by
ensuring that high-level modules depend on abstractions rather than concrete
implementations of lower-level modules. The Dependency Injection pattern is an
implementation of this principle
Example - The Dependency Injection
pattern is an implementation of this principle
No comments:
Post a Comment