Doubleton Design Pattern in C#: Part 2

I would like to share a way by which we can create a class that could create a maximum of two objects.

This could be an extension of the Singleton Pattern.

For more details of the C# Singleton Pattern kindly go through the following link.

Implementing Singleton in C#

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

For a previous article about the Doubleton Pattern, kindly following the link below.

Doubleton Design Pattern in C#

This article could be an extension of my last article.

Code Sample

Sealed class doubleton2

{

    private static readonly object doubletonLock = new object();

    private static int index = 0;

    private static List<doubleton2> list = new List<doubleton2>();

    private doubleton2() { }

    public static List<doubleton2> ReturnDoubletonList()

    {

        

         lock (doubletonLock)

         {

             if (index < 2)

             {

                 list.Add(new doubleton2());

                 index++;

              } 

          }

         return list; 

     }   

 }

class Program

{

    static void Main(string[] args)

    {

        List<doubleton2> lifirst = doubleton2.ReturnDoubletonList();

        List<doubleton2> lisecond= doubleton2.ReturnDoubletonList();

        List<doubleton2> lithird = doubleton2.ReturnDoubletonList();

       Console.ReadKey();

    }

}

Understanding the code

  1. We created a List object of the doubleton2 class
  2. On each call of the ReturnDoubletonList() method we are just incrementing the value of this static field (index integer)
  3. The ReturnDoubletonList () method is static and returns a List object of the Doubleton class
  4. We have index<2 inside the ReturnDoubletonList () method to ensure we can have a maximum of two objects of the doubleton class.
  5. After executing the first line of the main function:

    List<doubleton2> lifirst = doubleton2.ReturnDoubletonList();

    We have a list of one object.

    Creating List Object
  6. After executing the second line of the main function :

    List<doubleton2> liSecond = doubleton2.ReturnDoubletonList();

    We have a list of two objects.

    list of two objects
     
  7. After executing third line of the main function:

    List<doubleton2> lithird = doubleton2.ReturnDoubletonList();

    Again we have a list of two objects because we have the index<2 check in the ReturndoubetonList function.

    List index

Facts with the code

Here in the code above the following things can be seen.

The object lifirst[0] is always equal to lisecond[0].

If I added the following line to the main function:

Console.WriteLine("lifirst[0] and lisecond[0] are Equal: " + lifirst[0].Equals(lisecond[0]));

Then the following will be the output.

Output

Conclusion

Using the above we can learn how to create a doubleton class. Similarly we can create an N-ton class as well. We can modify this class as needed.


Similar Articles