Beruflich Dokumente
Kultur Dokumente
Design patterns offer proven ways to solve common architectural problems. There are many out
there and its 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 its useful to use a particular 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.
When the static method is called, first check if the private member thats of the same type of the
class is initialized. If it isnt, do so. Then return that member to the caller. Easy right?
return _Instance;
}
}
This is simple and works well. If you are writing a multi-threaded app though, this wont work.
Its not thread safe. Dont worry though. Its a simple enough to fix. All you need to do is obtain
a lock on a common object before initializing the instance. Locking a common object blocks any
other threads from accessing that code block until the current thread is done. Using this approach
ensures that no other threads access the single instance while its being initialized.
public class PaymentService
{
private static object _SyncRoot;
private static PaymentService _Instance;
private PaymentService()
{ }
return _Instance;
}
}