Skip to content

Commit 5ba4570

Browse files
feat: Implemented the Template View pattern (iluwatar#1320) (iluwatar#3110)
* pattern:implemented the Template View pattern (iluwatar#1320) * fix:added links in README and updated package name (iluwatar#1320) --------- Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>
1 parent ebcc070 commit 5ba4570

File tree

13 files changed

+635
-0
lines changed

13 files changed

+635
-0
lines changed

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218
<module>function-composition</module>
219219
<module>microservices-distributed-tracing</module>
220220
<module>microservices-idempotent-consumer</module>
221+
<module>templateview</module>
221222
<module>money</module>
222223
<module>table-inheritance</module>
223224
</modules>

templateview/README.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
title: "Template View Pattern in Java: Streamlining Dynamic Webpage Rendering"
3+
shortTitle: Template View
4+
description: "Learn about the Template View design pattern in Java, which simplifies webpage rendering by separating static and dynamic content. Ideal for developers building reusable and maintainable UI components."
5+
category: Behavioral
6+
language: en
7+
tag:
8+
- Abstraction
9+
- Code simplification
10+
- Decoupling
11+
- Extensibility
12+
- Gang of Four
13+
- Inheritance
14+
- Polymorphism
15+
- Reusability
16+
---
17+
18+
## Intent of Template View Design Pattern
19+
20+
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.
21+
22+
## Detailed Explanation of Template View Pattern with Real-World Examples
23+
24+
### Real-World Example
25+
26+
> 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.
27+
28+
### In Plain Words
29+
30+
> 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.
31+
32+
### Wikipedia Says
33+
34+
> 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.
35+
36+
## Programmatic Example of Template View Pattern in Java
37+
38+
Our example involves rendering different types of views (`HomePageView` and `ContactPageView`) with a common structure consisting of a header, dynamic content, and a footer.
39+
40+
### The Abstract Base Class: TemplateView
41+
42+
The `TemplateView` class defines the skeleton for rendering a view. Subclasses provide implementations for rendering dynamic content.
43+
44+
```java
45+
@Slf4j
46+
public abstract class TemplateView {
47+
48+
public final void render() {
49+
printHeader();
50+
renderDynamicContent();
51+
printFooter();
52+
}
53+
54+
protected void printHeader() {
55+
LOGGER.info("Rendering header...");
56+
}
57+
58+
protected abstract void renderDynamicContent();
59+
60+
protected void printFooter() {
61+
LOGGER.info("Rendering footer...");
62+
}
63+
}
64+
```
65+
### Concrete Class: HomePageView
66+
```java
67+
@Slf4j
68+
public class HomePageView extends TemplateView {
69+
70+
@Override
71+
protected void renderDynamicContent() {
72+
LOGGER.info("Welcome to the Home Page!");
73+
}
74+
}
75+
```
76+
### Concrete Class: ContactPageView
77+
```java
78+
@Slf4j
79+
public class ContactPageView extends TemplateView {
80+
81+
@Override
82+
protected void renderDynamicContent() {
83+
LOGGER.info("Contact us at: contact@example.com");
84+
}
85+
}
86+
```
87+
### Application Class: App
88+
The `App` class demonstrates rendering different views using the Template View pattern.
89+
```java
90+
@Slf4j
91+
public class App {
92+
93+
public static void main(String[] args) {
94+
TemplateView homePage = new HomePageView();
95+
LOGGER.info("Rendering HomePage:");
96+
homePage.render();
97+
98+
TemplateView contactPage = new ContactPageView();
99+
LOGGER.info("\nRendering ContactPage:");
100+
contactPage.render();
101+
}
102+
}
103+
```
104+
## Output of the Program
105+
```lessRendering HomePage:
106+
Rendering header...
107+
Welcome to the Home Page!
108+
Rendering footer...
109+
110+
Rendering ContactPage:
111+
Rendering header...
112+
Contact us at: contact@example.com
113+
Rendering footer...
114+
```
115+
## When to Use the Template View Pattern in Java
116+
- When you want to enforce a consistent structure for rendering views while allowing flexibility in dynamic content.
117+
- When you need to separate the static layout (header, footer) from the dynamic parts of a view (main content).
118+
- To enhance code reusability and reduce duplication in rendering logic.
119+
120+
## Benefits and Trade-offs of Template View Pattern
121+
**Benefits:**
122+
- Code Reusability: Centralizes shared layout logic in the base class.
123+
- Maintainability: Reduces duplication, making updates easier.
124+
- Flexibility: Allows subclasses to customize dynamic content.
125+
126+
**Trade-offs:**
127+
- Increased Number of Classes: Requires creating separate classes for each type of view.
128+
- Design Overhead: Might be overkill for simple applications with few views.
129+
130+
## Related Java Design Patterns
131+
- [Template Method](https://java-design-patterns.com/patterns/template-method/): A similar pattern focusing on defining a skeleton algorithm, allowing subclasses to implement specific steps.
132+
- [Strategy Pattern](https://java-design-patterns.com/patterns/strategy/): Offers flexibility in choosing dynamic behaviors at runtime instead of hardcoding them in subclasses.
133+
- [Decorator Pattern](https://java-design-patterns.com/patterns/decorator/): Can complement Template View for dynamically adding responsibilities to views.
134+
135+
## Real World Applications of Template View Pattern
136+
- Web frameworks like Spring MVC and Django use this concept to render views consistently.
137+
- CMS platforms like WordPress follow this pattern for theme templates, separating layout from content.
138+
139+
## References and Credits
140+
- [Effective Java](https://amzn.to/4cGk2Jz)
141+
- [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
142+
- [Refactoring to Patterns](https://amzn.to/3VOO4F5)
143+
- [Template Method Pattern](https://refactoring.guru/design-patterns/template-method)
144+
- [Basics of Django: Model-View-Template (MVT) Architecture](https://angelogentileiii.medium.com/basics-of-django-model-view-template-mvt-architecture-8585aecffbf6)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
@startuml
2+
package com.iluwater.templateview {
3+
class App {
4+
+ App()
5+
+ main(args : String[]) {static}
6+
}
7+
8+
abstract class TemplateView {
9+
- LOGGER : Logger {static}
10+
+ TemplateView()
11+
+ render() : void {final}
12+
# printHeader() : void
13+
# renderDynamicContent() : void {abstract}
14+
# printFooter() : void
15+
}
16+
17+
class HomePageView {
18+
- LOGGER : Logger {static}
19+
+ HomePageView()
20+
+ renderDynamicContent() : void
21+
}
22+
23+
class ContactPageView {
24+
- LOGGER : Logger {static}
25+
+ ContactPageView()
26+
+ renderDynamicContent() : void
27+
}
28+
}
29+
30+
App --> TemplateView
31+
TemplateView <|-- HomePageView
32+
TemplateView <|-- ContactPageView
33+
@enduml
43.8 KB
Loading

templateview/pom.xml

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
5+
6+
The MIT License
7+
Copyright © 2014-2022 Ilkka Seppälä
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
-->
28+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
29+
<modelVersion>4.0.0</modelVersion>
30+
<parent>
31+
<groupId>com.iluwatar</groupId>
32+
<artifactId>java-design-patterns</artifactId>
33+
<version>1.26.0-SNAPSHOT</version>
34+
</parent>
35+
<artifactId>templateview</artifactId>
36+
<dependencies>
37+
<dependency>
38+
<groupId>org.junit.jupiter</groupId>
39+
<artifactId>junit-jupiter-engine</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.mockito</groupId>
44+
<artifactId>mockito-inline</artifactId>
45+
<scope>test</scope>
46+
</dependency>
47+
</dependencies>
48+
<build>
49+
<plugins>
50+
<plugin>
51+
<groupId>org.apache.maven.plugins</groupId>
52+
<artifactId>maven-assembly-plugin</artifactId>
53+
<executions>
54+
<execution>
55+
<configuration>
56+
<archive>
57+
<manifest>
58+
<mainClass>com.iluwatar.templateview.App</mainClass>
59+
</manifest>
60+
</archive>
61+
</configuration>
62+
</execution>
63+
</executions>
64+
</plugin>
65+
</plugins>
66+
</build>
67+
</project>
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.templateview;
26+
27+
import lombok.extern.slf4j.Slf4j;
28+
29+
/**
30+
* Template View defines a consistent layout for rendering views, delegating dynamic content
31+
* rendering to subclasses.
32+
*
33+
* <p>In this example, the {@link TemplateView} class provides the skeleton for rendering views
34+
* with a header, dynamic content, and a footer. Subclasses {@link HomePageView} and
35+
* {@link ContactPageView} define the specific dynamic content for their respective views.
36+
*
37+
* <p>The {@link App} class demonstrates the usage of the Template View Pattern by rendering
38+
* instances of {@link HomePageView} and {@link ContactPageView}.
39+
*/
40+
@Slf4j
41+
public class App {
42+
43+
/**
44+
* Program entry point.
45+
*
46+
* @param args command line args
47+
*/
48+
public static void main(String[] args) {
49+
// Create and render the HomePageView
50+
TemplateView homePage = new HomePageView();
51+
LOGGER.info("Rendering HomePage:");
52+
homePage.render();
53+
54+
// Create and render the ContactPageView
55+
TemplateView contactPage = new ContactPageView();
56+
LOGGER.info("\nRendering ContactPage:");
57+
contactPage.render();
58+
}
59+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.templateview;
26+
27+
import lombok.extern.slf4j.Slf4j;
28+
29+
/**
30+
* ContactPageView implements the TemplateView and provides dynamic content specific to the contact page.
31+
*/
32+
@Slf4j
33+
public class ContactPageView extends TemplateView {
34+
35+
/**
36+
* Renders dynamic content for the contact page.
37+
*/
38+
@Override
39+
protected void renderDynamicContent() {
40+
LOGGER.info("Contact us at: contact@example.com");
41+
}
42+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.templateview;
26+
27+
import lombok.extern.slf4j.Slf4j;
28+
29+
/**
30+
* HomePageView implements the TemplateView and provides dynamic content specific to the homepage.
31+
*/
32+
@Slf4j
33+
public class HomePageView extends TemplateView {
34+
/**
35+
* Renders dynamic content for the homepage.
36+
*/
37+
@Override
38+
protected void renderDynamicContent() {
39+
LOGGER.info("Welcome to the Home Page!");
40+
}
41+
}

0 commit comments

Comments
 (0)