You work as the Enterprise application developer at Domain.com. The Domain.com network consists of a single Active Directory domain named Domain.com. All servers in the domain run Windows Server 2003. Your responsibilities at Domain.com include the testing and stabilization of applications. Domain.com operates in the security and surveillance environment. You are currently developing a video surveillance application for Domain.com.
You perform a code review of the following class:
public class Camera
{
public Camera GetInstance()
{
return _null;
}
}
This class is supposed to make use of the Singleton design pattern to control access to a physical video camera. You need to modify the Camera class.
What should you do? (Choose the correct code segment.)
A.
public class Camera
{
private static volatile Camera _instance;
public static Camera Instance
{
get
{
if (_instance = = null)
{
lock(_instance)
{
if (_instance = = null)
{
_instance = newCamera();
}
}
}
return _instance;
}
}
}
B.
public class Camera
{
private Camera _instance;
public Camera Instance
{
get
{
if (_instance = = null)
{
lock(_instance)
{
if (_instance = = null)
{
_instance = newCamera();
}
}
}
return _instance;
}
}
}
C.
public class Camera
{
public static Camera Instance
{
get
{
Camera instance = new Camera();
return instance;
}
]
}
D.
public class Camera
{
private Camera _instance;
public Camera GetInstance()
{
_instance = new Camera();
return _instance;
}
}
Explanation:
you need to define a static class member that returns a single instance of the class because the Singleton design pattern allows one instance of a class to be provided to multiple threads. The method must ensure that it creates an instance if there is not already an instance in existence and return the already existent instance if one does exist.
Incorrect answers:
B: This is incorrect you should be defining a static class member that returns a single instance of the class with the Singleton design pattern.
C: You should not implement a static property to always create a new instance of the class. You should rather return a single instance with the Singleton design pattern.
D: you should not be implementing a class member to return a non-static instance of the class. You need to return a static instance of the class with the Singleton design pattern.