Java中的单例和继承 [英] singleton and inheritance in Java

查看:109
本文介绍了Java中的单例和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,它捕获了两个类共同的一些功能。换句话说,我可以创建一个基类,并使这个基类的这两个子类。然而,对于这些子类中的每一个,可以创建的实例数为1(即每个子类必须是单例)。
我googled发现,这是一个合理的辩论。虽然有几种解决方案可供选择,但我不确定他们是否符合我的情况。



任何人都可以告诉我应该如何设计?

解决方案

使用抽象工厂模式。有一个单独的类有方法来检索单例,并让它保存对实例变量或地图中的单例的引用。



你可能不希望增加复杂性但是,为了解决这些问题(等等),创建了像 Spring 这样的框架。



似乎 Pico Container 活着还好,它可能是最简单的同时仍然是坚实的解决方案。看看控制的反转主题,让框架注入你需要的单身人士。



总之,不要试图使单身人员管理自己的访问。代表其他东西。



在复杂继承的单例类中没有内在的错误。实际上,具有私有构造函数(没有实例)的类层次结构在许多情况下是非常有用的。你只需要决定如何管理单身人士的两个重要方面:创作和访问。


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 class. However, for each of these sub classes, the number of instances can be created is 1 (i.e. each sub class has to be a singleton). I googled and found that there's a reasonable debate going on over this. Although there are several solutions available, I am not sure whether they would fit in my case.

can anyone tell me how I should design this?

解决方案

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.

这篇关于Java中的单例和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆