Difference between static class and singleton patt

2018-12-31 01:09发布

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?

30条回答
千与千寻千般痛.
2楼-- · 2018-12-31 02:01

When I want class with full functionality, e.g. there are many methods and variables, I use singleton;

If I want class with only one or two methods in it, e.g. MailService class, which has only 1 method SendMail() I use static class and method.

查看更多
浪荡孟婆
3楼-- · 2018-12-31 02:02

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, in my experience), so you can pass around the singleton as if it were "just another" implementation.

查看更多
谁念西风独自凉
4楼-- · 2018-12-31 02:02

In an article I wrote I have described my point of view about why the singleton is much better than a static class:

  1. Static class is not actually canonical class – it’s a namespace with functions and variables
  2. Using static class is not a good practice because of breaking object-oriented programming principles
  3. Static class cannot be passed as a parameter for other
  4. Static class is not suitable for “lazy” initialization
  5. Initialization and using of static class is always hard tracked
  6. Implementing thread management is hard
查看更多
栀子花@的思念
5楼-- · 2018-12-31 02:02
  1. We can create the object of singleton class and pass it to method.

  2. Singleton class doesn't any restriction of inheritance.

  3. We can't dispose the objects of a static class but can singleton class.

查看更多
有味是清欢
6楼-- · 2018-12-31 02:03

Singleton's are instantiated, it's just there's only one instance ever instantiated, hence the single in Singleton.

A static class can't be instantiated by anything other than itself.

查看更多
人气声优
7楼-- · 2018-12-31 02:03

Main differences are:

  • Singleton has an instance/object while static class is a bunch of static methods
  • Singleton can be extended e.g. through an interface while static class can't be.
  • Singleton can be inherited which supports open/close principles in SOLID principles on the other hand static class can't be inherited and we need to make changes in itself.
  • Singleton object can be passed to methods while static class as it does not have instance can't be passed as parameters
查看更多
登录 后发表回答