单例模式和静态类的区别

http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern

问题

What real (i.e. practical) difference exists between a static class and a singleton pattern?

Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?

 

第一个回答

What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

 

Imagine the singleton implements an interface Foo, and you have a method taking a Foo as a parameter.

With that setup, callers can choose to use the singleton as the implementation - or they could use a different implementation.

The method is decoupled解耦 from the singleton.

Compare that with the situation where the class just has static methods - every piece of code which wants to call those methods is tightly coupled to the class,

because it needs to specify which class contains the static methods. 

 

第二个回答

The true answer is by Jon Skeet, on another forum here.

A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.

 

posted @ 2014-10-30 09:50  ChuckLu  阅读(504)  评论(0编辑  收藏  举报