Laura Ruiz

Laura Ruiz

  • NA
  • 84
  • 949

Singleton Pattern and Global Variables

Jan 31 2024 11:07 PM

Hello community,

I have a question after reading a book on design patterns and researching online. I'm curious about why using the singleton pattern is often discouraged. I'm dealing with a scenario where I receive a request, and within that request, there's a specific form type, for example, Form-type1-virginia. The logic that needs to be executed corresponds to that particular state and form type, specifically type1.

I'm considering setting a global instance and accessing it to determine which validations should be executed. Is this a good solution? If not, what would be a better approach, or in which cases would you recommend using this design pattern or alternatively global variables? I would appreciate hearing your opinions on this.

Thanks.

Below is a snippet of the code I'm considering:

public class FormType
{
    private static FormType _instance;

    private string _type;
    private string _state;

    private FormType(string type, string state)
    {
        _type = type;
        _state = state;
    }

    public static FormType GetInstance(string type, string state)
    {
        if (_instance == null || (_instance._type != type || _instance._state != state))
        {
            _instance = new FormType(type, state);
        }
        return _instance;
    }

    public string Type => _type;
    public string State => _state;
}

 


Answers (2)