2013-06-27 51 views
0

我是Java新手,我對更高級的開發人員有幾個問題。是否可以 - 模擬此方法?

我有基於Swing的GUI應用程序,其中我有幾個AbstractActions。 一大羣AbstractActions根據JPanel創建新選項卡。例如:

// opens "Documents" tab 
documentsAction = new AbstractAction(DOCUMENTS) { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
    try { 
     int index = getTabIndex(DOCUMENTS); 
     if (index >= 0) { 
     // Tab exists, just open it. 
     tabbedPane.setSelectedIndex(index); 
     } else { 
     // No tab. Create it and open 
     newCatalogTab(new DocumentService(), DOCUMENTS); 
     } 
    } catch (ServiceException ex) { 
     printError(ex.getMessage()); 
    } 
    } 
}; 
documentsItem.setAction(documentsAction); 

其中getTabIndex是:

private int getTabIndex(String tabName) { 
    int result = -1; 
    for (int i = 0; i < tabbedPane.getTabCount(); i++) { 
     if (tabName.equals(tabbedPane.getTitleAt(i))) { 
     result = i; 
     break; 
     } 
    } 
    return result; 
    } 

newCatalogTab是:

private void newCatalogTab(ICatalog service, String Name) throws ServiceException { 
    CatalogPanel panel = new CatalogPanel(service); 
    tabbedPane.add(Name, panel); 
    tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); 
    checkTabs(); // changes activity of buttons like "edit" and "delete" 
    } 

因此,許多AbstractAction做類似的工作:

  1. 創建的實例上課,th在延伸AbstractPanel;
  2. 將數據訪問接口(示例中的DocumentService)傳遞給實例;
  3. 用實例創建一個新選項卡。

如果數據訪問接口使用不同的POJO,我可以以某種方式對此進行模板設計嗎? 我可以創建通用接口並使用它嗎? 你能向我展示思考的正確方向嗎?

感謝您浪費時間。

回答

1

Java中沒有模板,所以在任何情況下都會有一些代碼重複。但是,您可以使用factories來削減一些樣板代碼。例如:

interface CatalogFactory { 
    public ICatalog makeCatalog(); 
} 

class DocumentServiceFactory implements CatalogFactory { 
    @Override 
    public ICatalog makeCatalog() { 
     return new DocumentService(); 
    } 
} 

class TabAction extends AbstractAction { 
    private final String name; 
    private final CatalogFactory factory; 

    //Appropriate constructor... 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     //... 
     newCatalogTab(factory.makeCatalog(), name); 
     //... 
    } 
} 

然後,你可以做

documentsItem.setAction(new TabAction(DOCUMENTS, new DocumentServiceFactory())); 

,而不必爲每個標籤單獨匿名AbstractAction。

類似於面板和其他可能適合此模式的對象。

+0

好的。我想,我明白了。 – gooamoko

相關問題