【问题标题】:Send data from one module to another module with type safety使用类型安全将数据从一个模块发送到另一个模块
【发布时间】:2015-06-21 22:54:07
【问题描述】:

我的问题

什么设计可以让我在不缺乏类型安全的情况下在两个模块之间选择性地传递数据?这样的事情可能吗?

说明

我有 2 个从该类派生的模块

abstract class Module {
    public abstract void init(App app);
    public abstract void exit(App app);
    public abstract void process(App app);
    public abstract void paint(Graphics g);
}

App 类跟踪哪个模块是当前模块并允许该模块处理执行:

class App {
    private Map<Class<? extends Module>, Module> allModules = ...;
    private Module currentModule;

    //things to be used in modules
    private Canvas canvas;

    protected void start() {
        allModules.put(FirstModule.class, new FirstModule());
        //...

        currentModule = ...;
        currentModule.init(this);
    }

    protected void process() {
        currentModule.process(this);
    }

    protected void paint(Graphics g) {
        currentModule.paint(g);
    }

    public void switchModule(Class<? extends Module> module) {
        //perform validation
        Module next = allModules.get(module);

        currentModule.exit(this);
        currentModule = next;
        next.init(this);
    }

    //expose items that modules will use
    public Canvas getCanvas() {
        return canvas;
    }
}

现在,第一个模块负责收集用户指定的“设置”;它们将显示可供选择的复选框,然后单击一个按钮,该按钮存储有关选中哪个复选框的信息:

class First extends Module {
    private boolean firstBoxChecked, secondBoxChecked, thirdBoxChecked;

    public void init(App app) {
        canvas.addMouseListener(...);
    }

    public void process(App app) {
        if(buttonClicked) {
            app.switchModule(Second.class);
            //pass data to next module
        }
    }
}

所以在模块执行过程中的某个时刻,它会切换当前模块。有时我想在当前模块和我要切换到的模块之间传递数据(从第一个到第二个)。

我的尝试

我能想到的唯一“有效”方式是复制 Android 的切换活动设计(使用类似 Intent 的对象):

ModuleSwitchAction action = new ModuleSwitchAction(Second.class);
action.put("firstBoxChecked", "true");
//...
app.switchModule(action);

另一个班级的人需要知道确切的键名,如果他们搞砸了,在编译时没有任何警告。有没有更安全的方法来做到这一点?

【问题讨论】:

  • 看起来您想从超类型接口访问子类型实现差异。我不确定您是否能够像您所做的那样不使用地图来做到这一点。但是,您可以使用枚举类型实现映射的键,至少提供一些编译时类型安全。

标签: java oop module data-exchange


【解决方案1】:

我认为您正在寻找的是“责任链”设计模式。 在这里查看 - http://www.journaldev.com/1617/chain-of-responsibility-design-pattern-in-java-example-tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2023-03-29
    • 1970-01-01
    • 2019-07-18
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多