Java中具有子类的Singleton [英] Singleton with subclassing in java

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

问题描述

在Java中实现单例的最常见方法是使用私有构造函数和以下形式的公共访问器方法-

The most common way of implementing a singleton in java is to use a private constructor with a public accessor method of the form --

public class Singleton {
    private static Singleton instance = null;
    private Singleton() {

    }
    public static synchronized Singleton getInstance(){
        if (instance == null) {
        instance = new Singleton();         
        } 
        return instance;
    }
}

但是,由于构造函数是私有的,因此可以防止子类化单身人士。有什么方法可以使单例允许子类化?

However, since the constructor is private, it prevents subclassing the singleton. Is there any way in which we can make a singleton which allows subclassing ?

推荐答案

当您拥有类A扩展了B ,它是 A 的实例,实际上是包括 B 的实例。因此,继承的概念与单例模型相反。

When you have a class A extends B, an instance of A essentially "includes" instance of B. So the very concept of inheritance is contrary to the singleton model.

根据您的需要,我会考虑使用组合/委托。 (A将引用单例,而不是扩展其类)。如果由于某种原因需要继承,请使用Singleton方法创建一个接口,让Singleton实现该接口,然后让另一个类也实现该接口,并委派给Singleton以实现相关方法。

Depending on what you need it for, I would consider using composition / delegation. (A would have a reference to the singleton, rather than extending its class). If you need inheritance for some reason, create an interface with the Singleton methods, have Singleton implement that interface, and then have another class also implement that interface, and delegate to the singleton for its implementation of the relevant methods.

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

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