Doubleton Design Pattern in C#: Part 1

Introduction

I want to share a way to create a class that can create a maximum of two objects.

This could be an extension of the Singleton pattern.

For more details of C# patterns kindly go through the following link:

Implementing Singleton in C#

I want to introduce the following way to create a 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 the Code Sample:

Doubleton Design pattern

Understanding the code

  1. We created a static integer field: index to keep track of how many times the GetInstance() method has been called
  2. On each call of the GetInstance() method we are just incrementing the value of this static field (index integer)
  3. The GetInstance() method is static and it returns an object of the Doubleton class
  4. We have an index < 2 inside the GetInstance() method to ensure we can have a maximum of two objects of the doubleton class
  5. Inside Main, we are just creating multiple instances of the doubleton class
  6. The first two objects will be different and from the second onwards all objects will remain the same
  7. The GetInstance() method will return the same object after the second call

Fact with code above

If we are calling the GetInstance() method multiple times then after the second time of calling this method, it will return the last copy of the object. In other words it would return the copy of second object.

Conclusion

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

We can modify this class as needed.

Up Next
    Ebook Download
    View all
    Learn
    View all