Singleton pattern:A class in which only a single instance can exist.
using System;
using System.Collections.Generic;
using System.Text;
namespace SingletonPattern
{
public class Singleton
{
private static Singleton singletonInstance;
// Constructor is 'protected',so intance can't be created outside,
//only the createInstance() create the instance of Singleton class
protected Singleton()
{
}
public static Singleton createInstance()
{
if (singletonInstance == null)
{
singletonInstance = new Singleton();
}
return singletonInstance;
}
}
class Program
{
static void Main(string[] args)
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.createInstance();
Singleton s2 = Singleton.createInstance();
// Test for same instance
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
Console.ReadLine();
}
}
}
Output:
No comments:
Post a Comment