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;
}
}
No comments:
Post a Comment