如何将单例引用传递给十个同级对象
如果十个类继承自一个基类,并且所有十个子类都需要访问单例,那么应该如何传递对单例的引用。我看到了几种解决此问题的方法,其中两种是:
在超类中调用静态方法,该方法设置静态对象的引用,然后该静态对象可以由子类共享
将单例的引用作为其构造函数中的参数传递给每个子类。每个子类都可以存储对单例对象的引用,或者将其传递到超类构造函数中。
但我不知道什么是首选方式,或者我是否遗漏了一些明显的东西。提前致谢。
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:
Call a static method in the superclass that sets the reference of a static object which can then be shared by the subclasses
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不在单例类中使用 getInstance() 方法?你不需要传递它。每当您需要它时,请使用静态 getInstance() 方法。
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.
选项 1 可以减少代码中的噪音和重复。
Option 1 provides for less noise and duplication in your code.
如何在基类中创建单例实例,如下所示:
然后 mySingleton 在所有继承的类中自动可用。
编辑:根据您的评论:
您可以在基类中获取静态引用(如果不需要传递运行时参数),如下所示:
How about creating singleton instance in base class like this:
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: