This can be achieved by:
1. Making the constructor private/protected.
2. Create a static function which returns an instance of the class only after ensuring class has no other instance.
namespace OopConcept
{
///
/// Class without explicit contructor
///
class singleton
{
private static singleton singletonInstance = null;
///
/// To prevent instantiation.
///
private singleton()
{
}
public static singleton getInstance()
{
if (singletonInstance == null)
{
singletonInstance = new singleton();
}
return singletonInstance;
}
}
///
/// Main Class -
///
class MainClass
{
public static void Main()
{
// Cannot create an instance with 'new' Keyword.
singleton firstInstance = singleton.getInstance();
singleton secondInstance = singleton.getInstance();
if (firstInstance == secondInstance)
{
Console.WriteLine("Two instances are same");
Console.Read();
}
}
}
}
0 comments:
Post a Comment