-2

I need to complete the piece of code to write a method that takes a factory method that returns an object and determines if the object is a singleton instance.This is for an exercise of a course i am taking about design patterns. All the previous exercises were about implementing the pattern but this one is about testing and i dont know how to test this. I tried to create another instance and check if the hashcodes are the same but i dont know how to create another instance with that function.

 public class SingletonTester
{
  public static bool IsSingleton(Func<object> func)
  {
    // todo        
  }
}

ANSWER

.Net v1

    public class SingletonTester
    {
      private static int instanceId = 0;
      
      public static bool IsSingleton(Func<object> func)
      {
        var response = false;
        if(instanceId != func.GetHashCode()){
            response = true;
            instanceId = func.GetHashCode();
        }
        
        return response;
      }
    }
Biptor
  • 3
  • 2
  • Can you please tell us more about where and how you intend to use this method? – Klaus Gütter Jul 19 '22 at 17:59
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 19 '22 at 18:01
  • "Singleton" usually means "one and only instance" - the duplicate I picked explains difference between two approaches you could use to see if instances returned from to "create" calls are the same. If you have some other problem - please [edit] the question to clarify what exactly you want to check for "is singleton" and what is preventing you from writing such code. – Alexei Levenkov Jul 19 '22 at 19:51

1 Answers1

1

Singleton is a semantic definition, it is not generally testable through code. No interface can guarantee that the class operates as a singleton. Because of the semantic nature it would be better to create a custom annotation to indicate if the object is a singleton.