有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在两个命令处理程序之间通信

假设我有一个处理程序,通过侦听器将数据记录到某个对象

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

选择其中一个菜单项并开始记录到对象内部的数据结构时,将创建此对象

如何从其他处理程序检索此文档?如果有人用菜单停止录音,我需要这个


共 (1) 个答案

  1. # 1 楼答案

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

    您可能不能使用getter,因为正如您所提到的,处理程序是在执行菜单时创建的。我认为处理程序不是每次都重新创建的,只是在第一次访问时,所以可以在处理程序中创建一个实例变量,但这似乎不正确

    在这个阶段,将对象存储到数据库和序列化对您来说可能太过分了,所以我建议您使用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;
    }
    

    如果希望支持并发录制,以便可以同时打开多个文档,则需要一个解决方案来为每个文档生成密钥