Reputation: 995
I'm currently working on an application that has to render several Freemarker templates. So far I have a Generator class that handles the rendering. The class looks more or less like this:
public class Generator {
public static void generate(…) {
renderTemplate1();
renderTemplate2();
renderTemplate3();
}
private static void render(…) {
// renders the template
}
private static void renderTemplate1() {
// Create config object for the rendering
// and calls render();
};
private static void renderTemplate1() {
// Create config object for the rendering
// and calls render();
};
…
}
This works, but it doesn't really feel right. What I would like to do is create a class that holds all the renderTemplate...() methods and then call them dynamically from my Generator class. This would make it cleaner and easier to extend. I was thinking about using something like reflection, but it doesn't really feel like a good solution either. Any idea on how to implement this properly ?
Upvotes: 0
Views: 593
Reputation: 52185
You could have an interface with a defined method, render
which contains the logic to render the templates you are after.
Once that you have that, all your renderers will implement that method and have the required logic. Lastly, you could do something along the lines of this previous SO post to automatically look for and initialize your template classes.
For enhanced functionality, you could also combine the above with a .properties
file or a Database to allow certain templates to not be enabled automatically or to provide further initialization parameters.
Upvotes: 0
Reputation: 41188
Create a Renderer
interface.
Create an array containing Renderer
implementations.
Iterate over the array calling them all.
interface Renderer {
void renderTemplate();
}
static final Render[] renderers = new Render[] {
new Renderer {
public void renderTemplate() {
// Create config object for the rendering of 1
// and calls render();
}
},
new Renderer {
public void renderTemplate() {
// Create config object for the rendering of 2
// and calls render();
}
},
}
public static void generate() {
for (Renderer r: renderers) {
r.renderTemplate();
}
}
You might want to consider making Renderer
an abstract class and putting the Render method within it if it is shared by all the Renderer
implementations.
Upvotes: 2