Why use singleton instead of static class?

2019-01-22 01:37发布

When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that's not actually needed, but I'm sure there is a good reason. Otherwise, they wouldn't be used, obviously.

7条回答
走好不送
2楼-- · 2019-01-22 02:21

Even though IMHO the singleton pattern is a rather overused pattern, it does sometimes offer benefits, such as:

  • The ability to use different kinds of objects (that inherit from the same base) as the instance (think data providers where one uses the filesystem and one an SQL database, for example)
  • Serializability. I haven't used a framework that can automatically serialize static classes.
  • Using less static fields. For some people this is more of an esthetic feature, but in some cases it has practical benefits.
查看更多
登录 后发表回答