0

in a nutshell, i'm trying to build subclasses of an abstract class, all of which will be singletons. i'd like to just place the singleton "logic" in the super class. is this possible in Java? here is the code:

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>;
    }
}

and here is just a blurb for clarification of implementation:

public class CallTable extends Table {
    //this class would inherit 'getInstance()' and the method would return a 'CallTable' object
}
moonlightcheese
  • 10,664
  • 9
  • 49
  • 75

2 Answers2

1

There will only ever be one copy of the Table class (setting aside multiple classloaders etc!), so there will only be a single value m_Instance.

This means you can't have a singleton of each subclass - only a singleton of any one of the subclasses.

It would be possible to handle multiple subclasses e.g. by storing them in a Map in the superclass and looking them up by class, but the complexity is probably not worth it.

In either case, the getInstance method will return a Table, so you lose type safety - you may need to keep casting from Table to CallTable, for example. Java's type system doesn't support this kind of situation.

Also note that the singleton pattern is controversial, to say the least, and many folks try to avoid it.

DNA
  • 42,007
  • 12
  • 107
  • 146
1

i'd like to just place the singleton "logic" in the super class.

What logic? Simply follow the established idiom and define your Singletons with enums. It just works. No need to put Singleton logic in an abstract base class. enums already do all the work for you.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662