2014-06-08 27 views
0

简而言之,我试图构建一个抽象类的子类,所有这些都是单例。我想只把单身人士的“逻辑”放在超级班里。这在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 
} 

回答

1

只会有永远是Table类的一个副本(撇开多个类加载器等!),所以只有一个值m_Instance

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

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

在两种情况下,getInstance方法将返回一个Table,让你失去类型安全 - 你可能需要保持铸件从TableCallTable,例如。 Java的类型系统不支持这种情况。

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

1

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

什么逻辑?只需遵循the established idiom并用enum定义您的单身人士。它只是工作。不需要将Singleton逻辑放入抽象基类中。 enum已经为你做所有的工作。