articles

Doubleton Design pattern in C#

Devesh Omar6635 04-Jun-2014
Introduction

I would like to share a way by which we can create a class which could create

maximum two objects.

This could be extension of Singleton pattern.

I would like to introduce following way to create doubleton class.

Code Sample
public sealed class doubleton
    {
        private static doubleton _doubleton = null;
        private static readonly object doubletonLock = new object();
        private static int index = 0;
        private doubleton() { }
 
        public static doubleton GetInstance()
        {
            lock (doubletonLock)
            {
                if (index < 2)
                {
                    _doubleton = new doubleton();
                    index++;
                }
 
             }
            return _doubleton;
 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            doubleton ob1 = doubleton.GetInstance();
            doubleton ob2 = doubleton.GetInstance();
            doubleton ob3 = doubleton.GetInstance();
            doubleton ob4 = doubleton.GetInstance();
 
            Console.WriteLine("Obj1 and Obj2 are Equal: "+ob1.Equals(ob2));
            Console.WriteLine("Obj2 and Obj3 are Equal: " + ob2.Equals(ob3));
            Console.WriteLine("Obj3 and Obj4 are Equal: " + ob3.Equals(ob4));
            Console.ReadKey();
 
        }
    }

 

Output

Output of Code sample 1

Doubleton Design pattern in C#

 

Understanding the code

a.     We created static integer field: index to keep the track how many times GetInstance() method has been called.

b.    On each call of GetInstance() method we are just incrementing the value of this static field (index integer)

c.     GetInstance() method is static and it returns object of Doubleton class

d.      We have index<2 inside GetInstance() method to make sure we can have maximum two objects of doubleton class.

e.      Inside Main, we are just creating multiple instance of doubleton class

f.        First two objects would be different and from second onwards all the objects would remain same.

g.       GetInstance() method would return same object after second call.

Fact with above code

If we are calling GetInstance() method multiple times so after second time of calling this method, it would return last copy of object. Means it would return the copy of second object.

Conclusion

From above way we can learn how to create doubleton class. Similarly we can N-ton class as well.

We can modify this class as per requirement.

Thanks Happy coding


Updated 07-Sep-2019
I am Software Professional

Leave Comment

Comments

Liked By