-
-
Notifications
You must be signed in to change notification settings - Fork 26.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add CRTP pattern Ref: #2342 #2580
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
f56b6b7
Add crtp directory with builder for object hierarchy example Ref: #2342
4536e85
Add space package Ref: #2342
223a92f
Add comments for checkstyle Ref: #2342
75883f8
Add fight package as second crtp example Ref: #2342
97285eb
Add README.md Ref: #2342
1c412d0
Add use cases examples in README.md for crtp Ref: #2342
AddeusExMachina 7656213
Remove space package Ref: #2342
AddeusExMachina a7680bc
Move files from fight package to crtp Ref: #2342
AddeusExMachina f957f11
Add real world example in README.md Ref: #2342
AddeusExMachina 6683676
Update crtp README.md Ref: #2342
AddeusExMachina 033c283
Delete FighterTest Ref: #2342
AddeusExMachina b3413d7
Update App and AppTest in crtp Ref: #2342
AddeusExMachina 1fe6dde
Add category and tag in README.md frontmatter Ref: #2342
AddeusExMachina cae87c4
Add @Data annotation and remove constructor and toString in MmaFighte…
AddeusExMachina f6a9cda
Add FightTest Ref: #2342
AddeusExMachina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
/** | ||
* MmaBantamweightFighter class. | ||
*/ | ||
class MmaBantamweightFighter extends MmaFighter<MmaBantamweightFighter> { | ||
|
||
public MmaBantamweightFighter(String name, String surname, String nickName, String speciality) { | ||
super(name, surname, nickName, speciality); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
/* | ||
* 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.Data; | ||
import lombok.extern.slf4j.Slf4j; | ||
|
||
/** | ||
* MmaFighter class. | ||
* | ||
* @param <T> MmaFighter derived class that uses itself as type parameter. | ||
*/ | ||
@Slf4j | ||
@Data | ||
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; | ||
|
||
@Override | ||
public void fight(T opponent) { | ||
LOGGER.info("{} is going to fight against {}", this, opponent); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Check out for what else you can use Lombok for e.g. generate constructor, toString etc.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I replaced the constructor and toString() in MmaFighter with @DaTa annotation