Design patterns offer proven ways to solve common architectural problems. There are many out there and it’s probably not reasonable to expect a candidate to know them all. However, depending on the years of experience a candidate has, they should be able to tell you one or two they have used in the past and more importantly why it’s useful to use a particular pattern.
Now, let’s start with the singleton pattern.
The singleton pattern enforces that one and only one instance of a class will ever exist within an application. This is relatively easy to do.
- Make all constructors of the class private.
- Create a private static member that’s of the same type of the class.
- Create a public static member that returns and instance of that class.
When the static method is called, first check if the private member that’s of the same type of the class is initialized. If it isn’t, do so. Then return that member to the caller. Easy right?
public class PaymentService
{
// the only instance that can be initialized
private static PaymentService _Instance;// marked as private so no other classes can call the constructor
private PaymentService()
{ }// only public way of initializing the PaymentService class
public static PaymentService GetInstance()
{
// has the instance been intialized yet?
if (_Instance == null)
{
// no - so lets do it
_Instance = new PaymentService();
}
return _Instance;
}
}
public class PaymentService
{
private static object _SyncRoot;
private static PaymentService _Instance;
private PaymentService()
{ }
public static PaymentService GetInstance()
{
if (_Instance == null)
{
// obtain lock so no other threads can access it until the current thread is done
lock (_SyncRoot)
{
// is it still null? another thread may have initialized _Instance before
// the current thread obtained the lock
if (_Instance == null)
{
_Instance = new PaymentService();
}
}
}
return _Instance;
}
}
Nice article. If I execute the above code, I got the exception of type Null Reference Exception of line lock(_SyncRoot).
ReplyDeleteCan you please tell me how to sort it out this issue?
It ought to be:
ReplyDeleteprivate static object _SyncRoot = new object();
Wow! Such an amazing and helpful post this is. I really really love it. I hope that you continue to do your work like this in the future also.
ReplyDeleteApache Spark Training in Pune
Spark Training Institute in Pune
The writer understand better the mind of people what they want to learn through their writing therefore this article is outstanding. Thanks!!!
ReplyDeletebrand design SF
The Singleton pattern is a fundamental design pattern that ensures a class has only one instance throughout the application. Nordvpn With Gaming It's simplicity belies its power in managing shared implementing the Singleton pattern.
ReplyDelete