Send data from one module to another module with type safety

2.5k views Asked by At

My Question

What design would allow me to optionally pass data between two modules without the absence of type safety? Is such a thing possible?

Explanation

I have 2 modules derived from the class

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

The App class tracks which module is the current module and allows that module to handle execution:

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

Now, the first module is responsible for gathering "settings" specified by the user; they will be shown checkboxes to choose from, then click a button which stores info about which checkbox was checked:

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

So at some point during the execution of a module, it will switch the current module. There are times where I would want to pass data between the current module and the module I am switching to (from First to Second).

My Attempt

The only "efficient" way I can think of is to replicate Android's switching activities design (using an Intent like object):

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

The person in the other class would need to know the exact key names, without any warning at compile time if they messed something up. Is there a safer way to do this?

1

There are 1 answers

0
Raman Shrivastava On

I think what you're looking for is "chain of responsibility" design pattern. Check here - http://www.journaldev.com/1617/chain-of-responsibility-design-pattern-in-java-example-tutorial