2014-02-23 35 views
0

假设我有一个Handler通过侦听器将数据记录到某个对象。如何在两个命令处理程序之间进行通信

public Object execute(ExecutionEvent event) throws ExecutionException { 
    IHandlerService service; 
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); 
    try { 
     RecordingDocument d = new RecordingDocument("TestProject", "Tester", true); 
     d.record(); 
     MessageDialog.openInformation(
       window.getShell(), 
       "JavaTV", 
       "You are now recording."); 
    } catch (CoreException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

该对象是在选择某个菜单项并开始记录到对象内的数据结构时创建的。

如何从不同的处理程序中检索此文档?如果有人使用菜单停止录制,我需要这个。

回答

0

这似乎是一个关于如何使某些对象可被其他对象访问的普通Java问题。显然,你需要将它存储在一个可以被其他人访问的地方(提供一个getter,放到注册表,存储到数据库,序列化到硬盘等等)。有许多设计模式可以解决您的问题,因此无法提供理想的答案。

你不能,可能使用getters,因为正如你提到的Handler在执行菜单时创建的那样。我认为每次都不会重新创建处理程序,但只能在第一次访问时重新创建,所以您可以在处理程序中创建实例变量,但这看起来不正确。

存储到数据库和序列化在这个阶段对你来说可能过于矫枉过正,所以我建议你使用Registry pattern(把它想象成一个全局缓存)把对象放到注册表中。所以,这里是你能做什么:

public class DocumentsRegistry { 
    private Map<String, RecordingDocument> registry = new HashMap<String, RecordingDocument>(); 
    private static DocumentRegistry instace = new DocumentRegistry(); 

    public static DocumentRegistry getInstance() { 
     return instance; 
    } 

    public void registerDocument(String key, RecordingDocument document) { 
     registry.put(key, document); 
    } 

    public RecordingDocument getDocument(String key) { 
     return registry.get(key); 
    } 
} 

// your handler 

public static final String DOCUMENT_KEY = "DOCUMENT"; 

public Object execute(ExecutionEvent event) throws ExecutionException { 
    IHandlerService service; 
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); 
    try { 
     RecordingDocument d = new RecordingDocument("TestProject", "Tester", true); 
     d.record(); 
     MessageDialog.openInformation(
       window.getShell(), 
       "JavaTV", 
       "You are now recording."); 
     DocumentsRegistry.getInstance().registerDocument(DOCUMENT_KEY, d); 
    } catch (CoreException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

// another handler 
public Object execute(ExecutionEvent event) throws ExecutionException { 
    RecordingDocument d = DocumentsRegistry.getInstance().getDocument(DOCUMENT_KEY); 
    // do something with it 
    return null; 
} 

如果你想支持并发的录音,让很多文档可以在同一时间打开,你将需要为每个生成的密钥文件的解决方案。

相关问题