Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monostate vs. Singleton

What are the scenarios when one would use a Monostate pattern instead of singleton inorder to maintain a global object?

Edit: I know what Singleton and Monostate patterns are. Have also implemented Singleton in quite a few scenarios. Just want to know the scenarios (case examples) where MonoState pattern needs to be implemented.

For eg. I need to maintain list of columns per screen in my windows forms app. I could use a Singleton Dictionary in this case. However, I am storing a List in the static global var and I wanted to provide indexers (since I need to dynamically add new entry to the list if key is not present) where I could specify ScreenDetails.ScreenName as a key & get the ScreenDetails.ColumnsTable. Since indexers can't operate on a static class I changed the pattern to Monostate.

So I would like to know which other scenarios may compel a user to use Monostate instead of Singletons.

like image 787
SO User Avatar asked May 20 '09 11:05

SO User


People also ask

What is Monostate?

A monostate is a "conceptual singleton" - all data members of a monostate are static, so all instances of the monostate use the same (static) data. Applications using a monostate can create any number of instances that they desire, as each instance uses the same data.

Why should you avoid singletons?

By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.

When should you use singletons?

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

Why singleton pattern is used in C#?

One of the commonly used design patterns in C# is the singleton pattern. This design pattern uses a single instance of a class to enable global access to the class members. Instead of having several instances of the same class, singletons have just one instance, and provide convenient access to that single instance.


1 Answers

monostate and singleton are two faces of the same medal (global state):

  • monostate forces a behaviour (only one value along all class instances)
  • singleton forces a structural constraint (only one instance)

singleton usage is not transparent

i.e.:

Singleton singleton = Singleton.getInstance(); 

monostate usage is transparent

i.e.: MonoState m1 = new MonoState(); MonoState m2 = new MonoState(); // same internal state of m1 (e.g. static)
like image 156
dfa Avatar answered Sep 26 '22 10:09

dfa