开发者

How to pass a singleton reference to ten sibling objects

开发者 https://www.devze.com 2023-02-18 02:19 出处:网络
If ten classes inherit from a base class, and all ten of the subclasses need access to a singleton, how should the reference to the singleton be passed. I see several ways of going about this, two suc

If ten classes inherit from a base class, and all ten of the subclasses need access to a singleton, how should the reference to the singleton be passed. I see several ways of going about this, two such being:

  1. Call a static method in the superclass that sets the reference of a static object whi开发者_Go百科ch can then be shared by the subclasses

  2. Pass a reference of the singleton to each subclass as an argument in their constructors. Each subclass could store a reference to the singleton object, or pass it into the superclass constructor.

But I don't know what is the preferred way, or if I am missing something obvious. Thanks in advance.


Why not use the getInstance() method in your singleton class? You don't need to pass it along. Whenever you need it use the static getInstance() method.


Option 1 provides for less noise and duplication in your code.


How about creating singleton instance in base class like this:

static final MySingleton mySingleton = new MySingleton();

mySingleton is then automatically available in all the inherited classes.

EDIT: As per your comment:

You can get the static reference in base class (if it doesn't require passing runtime argument) like this:

static final MySingleton mySingleton;
static {
   SomeClass so = new SomeClass(123, "abc");
   mySingleton = so.getMySingleton();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消