Singleton vs Static Class for displaying data read from xml

We have a PageRoles XML file that contains the path to the page and the role of the user who can access that page.

We maintain a dictionary in a static class that loads an int static constructor for the class. The class has a CheckIfRoleAllowed method that takes the path to the page and returns a bool.

Each page calls CheckIfRoleAllowed on the Init page.

static class PageAccessChecker
{
 static Dictionary<string, UserRoleType[]> _PageAccessPermissions;
 static FileSystemWatcher _XmlWatcher;

 static PageAccessChecker()
 {
   // Load page access permissions from xml
   // Set FileSystemWatcher watcher to watch for changes
 }

 public static CheckIfRoleAllowed(string pagePath)
 {
 }

}

      

Wouldn't it be better to do this using the singleton pattern? If so, why?

Sincerely.

+1


source to share


4 answers


You are using a singleton. Simply, there are 2 common singles implementations, the other is an instance of a class and has a static member referencing that instance.

Your implementation makes the calls easier IMO:

PageAccessChecker.CheckIfRoleAllowed(path);

      



instead:

PageAccessChecker._default.CheckIfRoleAllowed(path);

      

+2


source


I see two benefits of using the singleton pattern (if implemented from, say, a static property):

  • you can defer loading the XML file until the first page is available.
  • you can check if the XML file has changed on disk and reload it automatically on next access.


The downside might be that you need to do threading access using blocking.

+3


source


In fact, you really don't want any singleton or static class.

First of all, a static class is singleton. I assume you are really asking, "Is it useful to add rigmarole to ensure that it is a security threat and there is only one, or, in other words, I need a" special "singleton? To which the answer is “No”, since you don't need a singleton.

Singleton is for objects where there can only be one , not for objects where only one is required. This is not the case here. There is nothing in this situation that requires a singleton. What you actually want is a thing called a "global variable".

"But wait!" you say. "Aren't global variables evil?" Well, yes, there is. But it does not matter. If you call it static class or singleon or whatever, then what you actually have here is a global variable. Calling it something else won't change anything.

+3


source


If you keep the class constructor private, there is no real difference - they are both global variables that can be lazy initialized.

If you keep the class constructor public or protected and only use the template to create a global one (not to enforce a single instance), you can at least check your singleton class.

But what you should really try is to avoid singles and use dependency injection instead. See Singletons are Mishko Heveri 's pathological liars .

-1


source







All Articles