Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

java - Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes:

  • Why would I create a singleton (stateless) instead of using static methods?
  • Why would an object instance be needed if an object has no state?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)

However, there are a few corner cases where even a stateless singleton can be useful:

  • You expect to extend it with state in the foreseeable future.
  • You need an object instance for some particular technical reason.
    Example: Synchonization objects for the C# lock or the Java synchronized statement.
  • You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.
    Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
  • You want reference equality for a sentinel value.
    Example: DBNull.Value in C#.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...