Implementing the singleton pattern in Java

前端 未结 6 754
一生所求
一生所求 2020-11-30 06:09

Can anyone provide an example of a singleton pattern and explain why they are necessary?

6条回答
  •  难免孤独
    2020-11-30 06:39

    One often underappreciated place where singletons are good is when you want to abstract away the existence of state. An example is a random number generator. At the level of the abstraction, it just generates random numbers and doesn't have any state that the caller should need to care about. At the implementation level, though, state is involved. Another is when a function caches results or intermediate computations, but you want to hide this detail from the caller.

    There is a significant tradeoff here. If you make things like these singletons, you decrease the amount of implementation details the caller of your function has to care about, thus decreasing coupling in that direction. However, at the same time you strongly couple your function to the singleton object, making it harder to test, etc. The decision about whether to use a singleton should be made based on which direction you care about reducing coupling in more.

提交回复
热议问题