2013-06-27 140 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

相关问题