templateview/README.md
Separate the structure and static parts of a webpage (or view) from its dynamic content. Template View ensures a consistent layout while allowing flexibility for different types of views.
Real-World Example
Think of a blog website where each post page follows the same layout with a header, footer, and main content area. While the header and footer remain consistent, the main content differs for each blog post. The Template View pattern encapsulates the shared layout (header and footer) in a base class while delegating the rendering of the main content to subclasses.
In Plain Words
The Template View pattern provides a way to define a consistent layout in a base class while letting subclasses implement the specific, dynamic content for different views.
Wikipedia Says
While not a classic Gang of Four pattern, Template View aligns closely with the Template Method pattern, applied specifically to rendering webpages or views. It defines a skeleton for rendering, delegating dynamic parts to subclasses while keeping the structure consistent.
Flowchart
Our example involves rendering different types of views (HomePageView and ContactPageView) with a common structure consisting of a header, dynamic content, and a footer.
The TemplateView class defines the skeleton for rendering a view. Subclasses provide implementations for rendering dynamic content.
@Slf4j
public abstract class TemplateView {
public final void render() {
printHeader();
renderDynamicContent();
printFooter();
}
protected void printHeader() {
LOGGER.info("Rendering header...");
}
protected abstract void renderDynamicContent();
protected void printFooter() {
LOGGER.info("Rendering footer...");
}
}
@Slf4j
public class HomePageView extends TemplateView {
@Override
protected void renderDynamicContent() {
LOGGER.info("Welcome to the Home Page!");
}
}
@Slf4j
public class ContactPageView extends TemplateView {
@Override
protected void renderDynamicContent() {
LOGGER.info("Contact us at: [email protected]");
}
}
The App class demonstrates rendering different views using the Template View pattern.
@Slf4j
public class App {
public static void main(String[] args) {
TemplateView homePage = new HomePageView();
LOGGER.info("Rendering HomePage:");
homePage.render();
TemplateView contactPage = new ContactPageView();
LOGGER.info("\nRendering ContactPage:");
contactPage.render();
}
}
Rendering header...
Welcome to the Home Page!
Rendering footer...
Rendering ContactPage:
Rendering header...
Contact us at: [email protected]
Rendering footer...
Benefits:
Trade-offs: