2
votes

I found something funny, I notice it by luck while I was debugging other thing. I was applying MVP pattern and I made a singleton controller to be shared among all presentations.

Suddenly I figured out that some event is called once at first postback, twice if there is two postback, 100 times if there is 100 postbacks.

because Singleton is based on a static variable which hold the instance, and the static variable live across postbacks, and I wired the event assuming that it will be wired once, and rewired for each postback.

I think we should think twice before applying a singleton in a web application, or I miss something??

thanks

3
MCP pattern? Do you mean MVP? But that doesn't have Controllers. Or perhaps MVC? But that doesn't have "presentations." And I've never heard of Singletons being involved in any of those. I think you're a little bit confused.Aaronaught
Your problem isn't that you used a "singleton", it's that you didn't thoroughly evaluate the meaning of your code. Understand the code you write, rather than using design patterns as "stamps" and translating them into syntax. They're guidelines, not stamps.user132014
I think the original Struts framework had a requirement that all the controllers be reusable across requests. I also recall it being the cause of quite a bit of grief for developers. Be careful with sharing the same object across requests (as you would with singletons).Roman
Can you all guys give code and trace too? It is impossible to judge anything from comments and answers, we agree right?xxxxxxxxxadfas

3 Answers

6
votes

You should think twice any time you are using static objects in a multi-threaded application (not only the singleton pattern) because of the shared state. Proper locking mechanisms should be applied in order to synchronize the access to the shared state. Failing to do so some very difficult to find bugs could appear.

10
votes

I would think twice about using a Singleton anywhere.

Many consider Singleton an anti-pattern.

Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

There are lots of references on Wikipedia that discuss this.

It is very rare to need a singleton and personally I hold them in the same light as global variables.

5
votes

I've been using Singletons in my web apps for quite some time and they have always worked out quite well for me, so to say they're a bad idea is really a pretty difficult claim to believe. The main idea, when using Singletons, is to keep all the session-specific information out of them, and to use them more for global or application data. To avoid them because they are "bad" is really not too smart because they can be very useful when applied correctly.