【问题标题】:building singletons from an abstract class从抽象类构建单例
【发布时间】:2014-06-08 08:20:06
【问题描述】:

简而言之,我正在尝试构建抽象类的子类,所有这些子类都将是单例。我只想将单例“逻辑”放在超类中。这在Java中可能吗?这是代码:

public abstract class Table {
    //the static singleton instance.  this will be inherited by subclasses of this class.
    protected static Table m_Instance;

    /**
     * @param tableName the database table name.
     */
    protected Table(String tableName, List<Column> columns) {
        TABLE_NAME = tableName;
        if(columns != null) {
            if(!m_Columns.isEmpty())
                m_Columns.clear();
            m_Columns.addAll(columns);
        } else {
            throw new IllegalStateException("the columns list was null.  this is a developer error.  please report to support.");
        }
    }

    protected static Table getInstance() {
        if(m_Instance == null)
            m_Instance = <? extends Table>;
    }
}

这里只是一个用于澄清实施的简介:

public class CallTable extends Table {
    //this class would inherit 'getInstance()' and the method would return a 'CallTable' object
}

【问题讨论】:

    标签: java inheritance reflection singleton


    【解决方案1】:

    Table 类将永远只有一个副本(除了多个类加载器等!),因此将只有一个值 m_Instance

    这意味着您不能拥有每个子类的单例 - 只有任何一个子类的单例。

    可以处理多个子类,例如通过将它们存储在超类中的Map 中并按类查找它们,但复杂性可能不值得。

    在任何一种情况下,getInstance 方法都会返回一个Table,因此您会失去类型安全性——例如,您可能需要继续从Table 转换为CallTable。 Java 的类型系统不支持这种情况。

    还请注意,单例模式至少可以说是有争议的,许多人试图避免它。

    【讨论】:

      【解决方案2】:

      我只想将单例“逻辑”放在超类中。

      什么逻辑?只需关注the established idiom 并使用enums 定义您的单身人士。它只是工作。无需将单例逻辑放在抽象基类中。 enums 已经为您完成了所有工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多