Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
trananso authored Oct 13, 2023
2 parents 0da0755 + b86f235 commit e6703e8
Show file tree
Hide file tree
Showing 16 changed files with 864 additions and 5 deletions.
30 changes: 29 additions & 1 deletion .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -2411,7 +2411,7 @@
"login": "saiteja55",
"name": "Saiteja Reddy",
"avatar_url": "https://avatars.githubusercontent.com/u/13088886?v=4",
"profile": "https://www.facebook.com/saiteja.reddy.94",
"profile": "https://www.linkedin.com/in/thisissaiteja/",
"contributions": [
"translation"
]
Expand Down Expand Up @@ -2614,6 +2614,34 @@
"contributions": [
"translation"
]
},
{
"login": "sanchitbansal10",
"name": "Sanchit Bansal",
"avatar_url": "https://avatars.githubusercontent.com/u/16536741?v=4",
"profile": "https://github.com/sanchitbansal10",
"contributions": [
"doc"
]
},
{
"login": "mm-saiful6854",
"name": "Md Saiful Islam",
"avatar_url": "https://avatars.githubusercontent.com/u/48361160?v=4",
"profile": "https://github.com/mm-saiful6854",
"contributions": [
"doc"
]
},
{
"login": "AddeusExMachina",
"name": "Antonio Addeo",
"avatar_url": "https://avatars.githubusercontent.com/u/39912670?v=4",
"profile": "https://github.com/AddeusExMachina",
"contributions": [
"doc",
"code"
]
}
],
"contributorsPerLine": 7,
Expand Down
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-287-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-289-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

<br/>
Expand Down Expand Up @@ -414,7 +414,7 @@ This project is licensed under the terms of the MIT license.
<td align="center" valign="top" width="14.28%"><a href="https://github.com/piyush280599"><img src="https://avatars.githubusercontent.com/u/118425491?v=4?s=100" width="100px;" alt="Piyush"/><br /><sub><b>Piyush</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=piyush280599" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/rahulraj90/"><img src="https://avatars.githubusercontent.com/u/517415?v=4?s=100" width="100px;" alt="Rahul Raj"/><br /><sub><b>Rahul Raj</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=rahul-raj" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/bharathkalyans/"><img src="https://avatars.githubusercontent.com/u/49526472?v=4?s=100" width="100px;" alt="Bharath Kalyan S"/><br /><sub><b>Bharath Kalyan S</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=bharathkalyans" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.facebook.com/saiteja.reddy.94"><img src="https://avatars.githubusercontent.com/u/13088886?v=4?s=100" width="100px;" alt="Saiteja Reddy"/><br /><sub><b>Saiteja Reddy</b></sub></a><br /><a href="#translation-saiteja55" title="Translation">🌍</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/thisissaiteja/"><img src="https://avatars.githubusercontent.com/u/13088886?v=4?s=100" width="100px;" alt="Saiteja Reddy"/><br /><sub><b>Saiteja Reddy</b></sub></a><br /><a href="#translation-saiteja55" title="Translation">🌍</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://twitch.tv/clerici"><img src="https://avatars.githubusercontent.com/u/115318468?v=4?s=100" width="100px;" alt="Enrique Clerici"/><br /><sub><b>Enrique Clerici</b></sub></a><br /><a href="#translation-TheClerici" title="Translation">🌍</a></td>
</tr>
<tr>
Expand Down Expand Up @@ -444,6 +444,11 @@ This project is licensed under the terms of the MIT license.
<td align="center" valign="top" width="14.28%"><a href="https://github.com/ibrahim89"><img src="https://avatars.githubusercontent.com/u/20753671?v=4?s=100" width="100px;" alt="Syyed Ibrahim Abdullah"/><br /><sub><b>Syyed Ibrahim Abdullah</b></sub></a><br /><a href="#translation-ibrahim89" title="Translation">🌍</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/JanisZhang"><img src="https://avatars.githubusercontent.com/u/95570096?v=4?s=100" width="100px;" alt="JiaDi Zhang"/><br /><sub><b>JiaDi Zhang</b></sub></a><br /><a href="#translation-JanisZhang" title="Translation">🌍</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/sanchitbansal10"><img src="https://avatars.githubusercontent.com/u/16536741?v=4?s=100" width="100px;" alt="Sanchit Bansal"/><br /><sub><b>Sanchit Bansal</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=sanchitbansal10" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/mm-saiful6854"><img src="https://avatars.githubusercontent.com/u/48361160?v=4?s=100" width="100px;" alt="Md Saiful Islam"/><br /><sub><b>Md Saiful Islam</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mm-saiful6854" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/AddeusExMachina"><img src="https://avatars.githubusercontent.com/u/39912670?v=4?s=100" width="100px;" alt="Antonio Addeo"/><br /><sub><b>Antonio Addeo</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=AddeusExMachina" title="Documentation">📖</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=AddeusExMachina" title="Code">💻</a></td>
</tr>
</tbody>
</table>

Expand Down
138 changes: 138 additions & 0 deletions crtp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
---
title: Curiously Recurring Template Pattern
language: en
category: Structural
tag:
- Extensibility
- Instantiation
---

## Name / classification

Curiously Recurring Template Pattern

## Also known as

Recursive Type Bound, Recursive Generic

## Intent

Allow derived components to inherit certain functionalities from a base component that are compatible with the derived type.

## Explanation

Real-world example

> For a mixed martial arts promotion that is planning an event, ensuring that the fights are organized between athletes
> of the same weight class is crucial. This prevents mismatches between fighters of significantly different sizes, such
> as a heavyweight facing off against a bantamweight.
In plain words

> Make certain methods within a type to accept arguments specific to its subtypes.
Wikipedia says

> The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X
> derives from a class template instantiation using X itself as a template argument.
**Programmatic example**

Let's define the generic interface Fighter

```java
public interface Fighter<T> {

void fight(T t);

}
```

The MMAFighter class is used to instantiate fighters distinguished by their weight class

```java
public class MmaFighter<T extends MmaFighter<T>> implements Fighter<T> {

private final String name;
private final String surname;
private final String nickName;
private final String speciality;

public MmaFighter(String name, String surname, String nickName, String speciality) {
this.name = name;
this.surname = surname;
this.nickName = nickName;
this.speciality = speciality;
}

@Override
public void fight(T opponent) {
LOGGER.info("{} is going to fight against {}", this, opponent);
}

@Override
public String toString() {
return name + " \"" + nickName + "\" " + surname;
}
```

The followings are some subtypes of MmaFighter

```java
class MmaBantamweightFighter extends MmaFighter<MmaBantamweightFighter> {

public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) {
super(name, surname, nickName, speciality);
}

}

public class MmaHeavyweightFighter extends MmaFighter<MmaHeavyweightFighter> {

public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) {
super(name, surname, nickName, speciality);
}

}
```

A fighter is allowed to fight an opponent of the same weight classes, if the opponent is of a different weight class
there is an error

```java
MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai");
MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo");
fighter1.fight(fighter2); // This is fine

MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing");
MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu");
fighter3.fight(fighter4); // This is fine too

fighter1.fight(fighter3); // This will raise a compilation error
```

## Class diagram

![alt text](./etc/crtp.png "CRTP class diagram")

## Applicability

Use the Curiously Recurring Template Pattern when

* You have type conflicts when chaining methods in an object hierarchy
* You want to use a parameterized class method that can accept subclasses of the class as arguments, allowing it to be applied to objects that inherit from the class
* You want certain methods to work only with instances of the same type, such as for achieving mutual comparability.

## Tutorials

* [The NuaH Blog](https://nuah.livejournal.com/328187.html)
* Yogesh Umesh Vaity answer to [What does "Recursive type bound" in Generics mean?](https://stackoverflow.com/questions/7385949/what-does-recursive-type-bound-in-generics-mean)

## Known uses

* [java.lang.Enum](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Enum.html)

## Credits

* [How do I decrypt "Enum<E extends Enum<E>>"?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106)
* Chapter 5 Generics, Item 30 in [Effective Java](https://www.amazon.com/gp/product/0134685997/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0134685997&linkCode=as2&tag=javadesignpat-20&linkId=4e349f4b3ff8c50123f8147c828e53eb)
Binary file added crtp/etc/crtp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions crtp/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
The MIT License
Copyright © 2014-2022 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>crtp</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.crtp.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
52 changes: 52 additions & 0 deletions crtp/src/main/java/crtp/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package crtp;

import lombok.extern.slf4j.Slf4j;

/**
* Shows the {@link Fighter} fight method call on some implementations of {@link MmaFighter}. Note
* that fighters can only fight against opponents of their same weight class.
*/
@Slf4j
public class App {

/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {

MmaBantamweightFighter fighter1 = new MmaBantamweightFighter("Joe", "Johnson", "The Geek", "Muay Thai");
MmaBantamweightFighter fighter2 = new MmaBantamweightFighter("Ed", "Edwards", "The Problem Solver", "Judo");
fighter1.fight(fighter2);

MmaHeavyweightFighter fighter3 = new MmaHeavyweightFighter("Dave", "Davidson", "The Bug Smasher", "Kickboxing");
MmaHeavyweightFighter fighter4 = new MmaHeavyweightFighter("Jack", "Jackson", "The Pragmatic", "Brazilian Jiu-Jitsu");
fighter3.fight(fighter4);

}
}
36 changes: 36 additions & 0 deletions crtp/src/main/java/crtp/Fighter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package crtp;

/**
* Fighter interface.
*
* @param <T> The type of fighter.
*/
public interface Fighter<T> {

void fight(T t);

}
Loading

0 comments on commit e6703e8

Please sign in to comment.