开发者

Singleton pattern with Web application, Not a good idea!

开发者 https://www.devze.com 2022-12-27 22:04 出处:网络
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.

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 apply开发者_如何学Cing a singleton in a web application, or I miss something??

thanks


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号