singleton and inheritance in Java

前端 未结 6 601
鱼传尺愫
鱼传尺愫 2021-01-17 16:30

I have a base class that captures some functionality common to two classes. In other words, I can create one base class and make these two classes subclasses of that base cl

6条回答
  •  孤城傲影
    2021-01-17 17:08

    Use the Abstract factory pattern. Have a separate class with methods to retrieve the singletons, and let it hold the references to the singletons in instance variables or in a map.

    You may not want the increased complexity, but frameworks like Spring were created to solve these kind of issues (among others).

    It seems that Pico Container is alive and well, and it may be the simplest while still solid solution. Look at the inversion of control topics, and let the framework inject the singletons where you need them.

    In short, don't try to make the singletons manage access to themselves. Delegate that on something else.

    There's nothing inherently wrong in having singleton classes with complex inheritance. In fact, class hierarchies with private constructors (no instances) are very useful in many situations. You just have to decide how you want to manage the two important aspects of singletons: creation, and access.

提交回复
热议问题