Singleton Pattern:This is a part of the Creation Pattern. This pattern ensures that you have only one instance and provides a single point of contact to access the instance.As per of GOF Definition:Ensure a class has only one instance and provide a global point of access to it.UML Class Diagram: Singleton Class:
//Constructor should be private to avoid the further instance creation, as this class is already have an instance. private MathUtility() { }
//Create a static propery to get the already created instance of this class. public static MathUtility Instance { get { return _instance; } }
private int _firstInput; public int FirstInput { get { return _firstInput; } set { _firstInput = value; } }
private int _secondInput; public int SecondInput { get { return _secondInput; } set { _secondInput = value; } } public int Add() { return _firstInput + _secondInput; } }}
static void Main(string[] args) { MathUtility mathUtilInstance1 = MathUtility.Instance;
mathUtilInstance1.FirstInput = 1; mathUtilInstance1.SecondInput = 2;
Console.WriteLine("Addition Value from First Instance: {0}", mathUtilInstance1.Add());
MathUtility mathUtilInstance2 = MathUtility.Instance;
Console.WriteLine("Addition Value from Second Instance: {0}", mathUtilInstance1.Add());
if (mathUtilInstance1 == mathUtilInstance2) { Console.WriteLine("Both Instance are equal"); } Console.ReadLine(); }
//Create a propery, this propery will return the instance if this is not already created public static MathUtility Instance { get { lock (typeof(MathUtility)) { if (_instance == null) { _instance = new MathUtility(); } return _instance; } } }
private int _secondInput; public int SecondInput { get { return _secondInput; } set { _secondInput = value; } } public int Add() { return _firstInput + _secondInput;; } }
class Program { static void Main(string[] args) { Console.WriteLine("Main Program Starts"); MathUtility mathUtilInstance1 = MathUtility.Instance; mathUtilInstance1.FirstInput = 1; mathUtilInstance1.SecondInput = 2; Console.WriteLine("Addition Value from First Instance: {0}", mathUtilInstance1.Add()); MathUtility mathUtilInstance2 = MathUtility.Instance; Console.WriteLine("Addition Value from Second Instance: {0}", mathUtilInstance1.Add()); if (mathUtilInstance1 == mathUtilInstance2) { Console.WriteLine("Both Instance are equal"); } Console.ReadLine(); } }
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: