Design Patterns – Best Practices for Manager Type Classes

abstractiondesign-patternsobject-oriented

I have a class that I usually end up calling XManager. This class usually acts a dispatcher. Where it will read a config and do what the config says.

Assuming that I have the following class structure:

-Manger
 | - Phases
   | - PhaseX implements Phase { void run(); }
   | - PhaseY implements Phase { void run(); }
   | - PhaseZ implements Phase { void run(); }
 PhaseManager

In PhaseManager I have some code that looks like:

class PhaseManager {
    private Set<Phase> phases;

    public PhaseManager(Config config) {
        // Use config to instantiate all enabled phases, adding them to phases.
    }

    public void runPhases() {
        for(Phase p : phases) {
            p.run();
        }
    }
}

And thus in my main.java I'd have something like:

PhaseManager manager = new PhaseManager(config);
manager.runPhases();

But I'm convinced there is a better way. And after reading many of the design patterns I cannot figure out exactly to which design pattern this best fits.

It looks like it could be callback, but not really; as there is no action that occurs to initiate this, it just has to happen.

It could be command, but it seems like command is a bit overkill for this approach.

Best Answer

I think the same can (and likely should) be expressed cleaner using the builder pattern.

Result result = InitialPhase.fromConfig(config)
                            .phase1(...)
                            .phase2(...)
                            // ...
                            .build();

Each .phaseN() method may return a class that only allows to invoke the correct next phase(s). (In the "PhaseManager" design it is possible to run the phases in arbitrary order.) Each .phaseN(...) may accept whatever phase-specific parameters there may be.

The final .build() makes the resulting object from a phase object. If the subject area permits, several phases can provide a .build() method, allowing for different build paths.

Related Topic