Compare commits

...

31 Commits

Author SHA1 Message Date
5286834b37 docs: fixes for yaml frontmatter 2021-10-12 15:13:08 +03:00
d247b6ed69 docs: add VxDxK as a contributor for translation (#1848)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-10-11 21:45:21 +03:00
0a73ead12d translation: Add Russian translation (#1846)
* Add ru url to README.md

* Create russian README.md
2021-10-11 21:43:58 +03:00
ddb9b14eed docs: add muklasr as a contributor for translation (#1845)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-10-08 20:47:25 +03:00
0255111b4e translation: Add Indonesian translation (#1841)
* Create README.md in id

* Add README.md in id url
2021-10-08 20:45:59 +03:00
9513d2be58 docs: add Conhan93 as a contributor for doc (#1844)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-10-08 20:36:02 +03:00
119abf3ee4 Doc: Corrected a few spelling mistakes (#1840) 2021-10-08 20:34:47 +03:00
87cc4df14b docs: Add frascu as a Contributor for Code (#1835)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-10-05 10:07:07 +05:30
57f9c2e968 task: Update Lombok to version 1.18.20 (#1828)
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-10-05 10:05:20 +05:30
42eb7950ae task: Fix broken links (#1817)
* Fix some broken links

* Remove extra space

* Update filename

* Fix some links in localization folders

* Fix link

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-09-29 00:13:31 +05:30
be72a96cd6 docs: add tan31989 as a contributor for code (#1820)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-09-29 00:11:14 +05:30
be25c0b433 bug-fix: Use Junit5 in the serverless module tests (#1794)
* #1667: Fixing the serverless tests to use Junit5 and also modifying other classes to remove the deprecated initMock() method

* #1667: Fixing the sonar code smells

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-09-29 00:09:19 +05:30
be59e50205 doc: Fix Typos in French local doc (#1818)
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-09-28 21:49:30 +05:30
ec90320eda docs: add mortezaadi as a contributor for code (#1816)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-09-07 21:46:23 +03:00
3126ad3106 fix: Remove unnecessary and possibly not threadsafe flag (#1811) 2021-09-07 21:43:47 +03:00
e2ebb59fe7 docs: add karthikbhat13 as a contributor for code (#1808)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-08-08 15:53:13 +03:00
d87e8cf10d feature: Added FanOut/FanIn Pattern (#1800)
* Added FanOut/FanIn Pattern (#8)

* #1627 adding fanout-fanin pattern

* #1627 adding class diagram image

* #1627 adding readme

* #1627 adding license

* #1627 updating relations

* #1627 interrupting the thread

* #1627 fixing sonar issues

* #1627 fixing sonar issues

* #1627 adding more info in README.md

* Added FanOut/FanIn (#9)

* #1627 adding fanout-fanin pattern

* #1627 adding class diagram image

* #1627 adding readme

* #1627 adding license

* #1627 updating relations

* #1627 interrupting the thread

* #1627 fixing sonar issues

* #1627 fixing sonar issues

* #1627 adding more info in README.md

* #1627 adding programmatic examples in README.md
2021-08-08 15:51:27 +03:00
c5a4068e84 docs: Translation for zh (#1805)
* add state and callback pattern

* add command and template-method pattern

* add iterator pattern

* add bridege and DI pattern

* fix issue #1600

* add converter,proxy,visitor pattern

* add caching,composite,delegation,dirty-flag,interpreter patterns

* add dao and producer-consumer

* add dto and provate class data pattern

* fix #1646 png path problems

* fix #1646 composite png path case problem

* add abstract document pattern and version-number pattern

* add ambassador pattern

* add acyclic-visitor and api-gateway pattern

* add abstract-factory pattern

* add active-object pattern

* add aggregator-microservices and arrange-act-assert pattern

* update async-method-invocation pattern

* add balking and business-delegate pattern

* add bytecode and circuit-break pattern

* update arrange/act/assert pattern problems

* add csch pattern

* add language code, correct pic path

* #1805 update permalink

Co-authored-by: Subhrodip Mohanta <subhrodipmohanta@gmail.com>
Co-authored-by: Mike <admin@xiaod.info>
Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>
2021-08-01 20:25:54 +05:30
d36efdbc7c TASK: Add language to yaml front matter (#1806) 2021-07-25 17:28:54 +05:30
3f654ab0c8 docs: add AndriyPyzh as a contributor for code (#1804)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-07-22 17:00:52 +03:00
eac85678f0 feature: Added Domain Model pattern (#1795)
* domain-model pattern

* fixed optional get before check isPresent

* readme minor changes

* change currency representation with joda money

* changed names of test methods

* fixed code smells

* Update domain-model/README.md

Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>

* Update domain-model/README.md

Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>

* updated readme and diagrams

Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>
2021-07-22 16:58:21 +03:00
eaeb6e717c docs: add marlo2222 as a contributor for translation (#1798)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-07-09 10:47:34 +03:00
28fc672a2f translation: portuguese translation and languages codes (#1792)
* portuguese translation and languages codes

* fix unlinked links

Co-authored-by: Marlo Henrique de Lima Oliveira <marlo.oliveira@rsinet.com.br>
2021-07-09 10:44:06 +03:00
04bf566dc1 task: Explanations and grammar fixes for all the GoF patterns (#1791)
* Grammatical fixes to command pattern

* Update bridge pattern readme

* Fixes to builder pattern grammar

* Update chain of responsibility

* Improvements to the composite example

* Fixes to headings

* Minor updates to decorator pattern

* Update facade

* Update factory example

* Update factory method

* Update flyweight

* Interpreter explanation

* Update iterator readme

* Add explanation for mediator pattern

* Grammatical fixes to memento

* Grammar fixes for observer

* Update explanation for the prototype pattern

* Proxy pattern grammar fixes

* Update singleton

* Grammar fixes to state pattern

* Grammar fixes for strategy

* Grammar fixes, template method

* Grammar fixes for visitor

* Fix typo
2021-06-24 18:27:20 +05:30
bbdff14a66 Fix: Fixing License issue in MVVM pattern (#1701)
* Fixing License issue in MVVM pattern

* Updating LICENSE.md

* Updating pom.xml

* License header update to MVVM module only.

* Updating pom and removing gpl txt

* Adding gpl txt file

Co-authored-by: Jinisha <Jinisha@LAPTOP-VG38PNMC.fios-router.home>
2021-06-08 21:40:24 +03:00
eade10a98d docs: add samuelpsouza as a contributor (#1785)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-06-07 22:32:23 +05:30
43e7ca515a refactor: #1012 - Resolve Sonar report: missing assertions in several AppTest classes (#1784)
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-06-07 22:30:44 +05:30
f6d43975fa docs: Grammatical fixes for Abstract Factory (#1782)
* Grammatical fixes

* Update abstract-factory/README.md

Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
2021-06-05 13:03:25 +05:30
c0d36894c2 docs: add Xenilo137 as a contributor (#1781)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-06-04 21:54:17 +03:00
6cf025447a fix: change 'swinged' to 'swung' in sword.java and hammer.java of bridge pattern (#1779)
* minor (non-coding) change

* Update Sword.java
2021-06-04 21:50:40 +03:00
dafe02f1be docs: add JuanManuelAbate as a contributor (#1780)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-06-04 21:39:47 +03:00
208 changed files with 6081 additions and 775 deletions

View File

@ -1523,6 +1523,114 @@
"contributions": [
"code"
]
},
{
"login": "JuanManuelAbate",
"name": "Juan Manuel Abate",
"avatar_url": "https://avatars.githubusercontent.com/u/16357060?v=4",
"profile": "https://github.com/JuanManuelAbate",
"contributions": [
"translation"
]
},
{
"login": "Xenilo137",
"name": "Xenilo137",
"avatar_url": "https://avatars.githubusercontent.com/u/24865069?v=4",
"profile": "https://github.com/Xenilo137",
"contributions": [
"code"
]
},
{
"login": "samuelpsouza",
"name": "Samuel Souza",
"avatar_url": "https://avatars.githubusercontent.com/u/17254162?v=4",
"profile": "https://www.linkedin.com/in/souzasamuel/",
"contributions": [
"code"
]
},
{
"login": "marlo2222",
"name": "Marlo Henrique",
"avatar_url": "https://avatars.githubusercontent.com/u/40809563?v=4",
"profile": "https://github.com/marlo2222",
"contributions": [
"translation"
]
},
{
"login": "AndriyPyzh",
"name": "AndriyPyzh",
"avatar_url": "https://avatars.githubusercontent.com/u/57706635?v=4",
"profile": "https://github.com/AndriyPyzh",
"contributions": [
"code"
]
},
{
"login": "karthikbhat13",
"name": "karthikbhat13",
"avatar_url": "https://avatars.githubusercontent.com/u/22431014?v=4",
"profile": "https://github.com/karthikbhat13",
"contributions": [
"code"
]
},
{
"login": "mortezaadi",
"name": "Morteza Adigozalpour",
"avatar_url": "https://avatars.githubusercontent.com/u/1329687?v=4",
"profile": "https://github.com/mortezaadi",
"contributions": [
"code"
]
},
{
"login": "tan31989",
"name": "Nagaraj Tantri",
"avatar_url": "https://avatars.githubusercontent.com/u/3784194?v=4",
"profile": "https://stackoverflow.com/users/308565/nagaraj-tantri",
"contributions": [
"code"
]
},
{
"login": "frascu",
"name": "Francesco Scuccimarri",
"avatar_url": "https://avatars.githubusercontent.com/u/7107651?v=4",
"profile": "http://scuccimarri.it",
"contributions": [
"code"
]
},
{
"login": "Conhan93",
"name": "Conny Hansson",
"avatar_url": "https://avatars.githubusercontent.com/u/71334757?v=4",
"profile": "https://github.com/Conhan93",
"contributions": [
"doc"
]
},
{
"login": "muklasr",
"name": "Muklas Rahmanto",
"avatar_url": "https://avatars.githubusercontent.com/u/43443753?v=4",
"profile": "http://muklasr.medium.com",
"contributions": [
"translation"
]
},
{
"login": "VxDxK",
"name": "Vadim",
"avatar_url": "https://avatars.githubusercontent.com/u/38704817?v=4",
"profile": "https://github.com/VxDxK",
"contributions": [
"translation"
]
}
],
"contributorsPerLine": 4,

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2014-2021 Ilkka Seppälä
Copyright <EFBFBD> 2014-2021 Ilkka Sepp<EFBFBD>l<EFBFBD>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -19,3 +19,6 @@ 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.
Module Model-view-viewmodel is using ZK framework
ZK framework is licensed under LGPL and the license can be found at lgpl-3.0.txt

View File

@ -10,12 +10,12 @@
[![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-167-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-179-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<br/>
Read in different language : [**zh**](/localization/zh/README.md), [**ko**](/localization/ko/README.md), [**fr**](/localization/fr/README.md), [**tr**](/localization/tr/README.md), [**ar**](/localization/ar/README.md), [**es**](/localization/es/README.md)
Read in different language : [**zh**](localization/zh/README.md), [**ko**](localization/ko/README.md), [**fr**](localization/fr/README.md), [**tr**](localization/tr/README.md), [**ar**](localization/ar/README.md), [**es**](localization/es/README.md), [**pt**](localization/pt/README.md), [**id**](localization/id/README.md), [**ru**](localization/ru/README.md)
<br/>
@ -325,6 +325,24 @@ This project is licensed under the terms of the MIT license.
<td align="center"><a href="https://github.com/JackieNim"><img src="https://avatars.githubusercontent.com/u/4138836?v=4?s=100" width="100px;" alt=""/><br /><sub><b>JackieNim</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=JackieNim" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/EdisonE3"><img src="https://avatars.githubusercontent.com/u/52118917?v=4?s=100" width="100px;" alt=""/><br /><sub><b>EdisonE3</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=EdisonE3" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/tao-sun2"><img src="https://avatars.githubusercontent.com/u/66189688?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tao</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=tao-sun2" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/JuanManuelAbate"><img src="https://avatars.githubusercontent.com/u/16357060?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Juan Manuel Abate</b></sub></a><br /><a href="#translation-JuanManuelAbate" title="Translation">🌍</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Xenilo137"><img src="https://avatars.githubusercontent.com/u/24865069?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Xenilo137</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Xenilo137" title="Code">💻</a></td>
<td align="center"><a href="https://www.linkedin.com/in/souzasamuel/"><img src="https://avatars.githubusercontent.com/u/17254162?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Samuel Souza</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=samuelpsouza" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/marlo2222"><img src="https://avatars.githubusercontent.com/u/40809563?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Marlo Henrique</b></sub></a><br /><a href="#translation-marlo2222" title="Translation">🌍</a></td>
<td align="center"><a href="https://github.com/AndriyPyzh"><img src="https://avatars.githubusercontent.com/u/57706635?v=4?s=100" width="100px;" alt=""/><br /><sub><b>AndriyPyzh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=AndriyPyzh" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/karthikbhat13"><img src="https://avatars.githubusercontent.com/u/22431014?v=4?s=100" width="100px;" alt=""/><br /><sub><b>karthikbhat13</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=karthikbhat13" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/mortezaadi"><img src="https://avatars.githubusercontent.com/u/1329687?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Morteza Adigozalpour</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=mortezaadi" title="Code">💻</a></td>
<td align="center"><a href="https://stackoverflow.com/users/308565/nagaraj-tantri"><img src="https://avatars.githubusercontent.com/u/3784194?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nagaraj Tantri</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=tan31989" title="Code">💻</a></td>
<td align="center"><a href="http://scuccimarri.it"><img src="https://avatars.githubusercontent.com/u/7107651?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Francesco Scuccimarri</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=frascu" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Conhan93"><img src="https://avatars.githubusercontent.com/u/71334757?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Conny Hansson</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Conhan93" title="Documentation">📖</a></td>
<td align="center"><a href="http://muklasr.medium.com"><img src="https://avatars.githubusercontent.com/u/43443753?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Muklas Rahmanto</b></sub></a><br /><a href="#translation-muklasr" title="Translation">🌍</a></td>
<td align="center"><a href="https://github.com/VxDxK"><img src="https://avatars.githubusercontent.com/u/38704817?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vadim</b></sub></a><br /><a href="#translation-VxDxK" title="Translation">🌍</a></td>
</tr>
</table>

View File

@ -20,9 +20,9 @@ objects without specifying their concrete classes.
## Explanation
Real world example
Real-world example
> To create a kingdom we need objects with a common theme. Elven kingdom needs an Elven king, Elven castle and Elven army whereas Orcish kingdom needs an Orcish king, Orcish castle and Orcish army. There is a dependency between the objects in the kingdom.
> To create a kingdom we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom.
In plain words
@ -34,7 +34,7 @@ Wikipedia says
**Programmatic Example**
Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the
Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the
kingdom.
```java
@ -52,21 +52,21 @@ public interface Army {
// Elven implementations ->
public class ElfCastle implements Castle {
static final String DESCRIPTION = "This is the Elven castle!";
static final String DESCRIPTION = "This is the elven castle!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfKing implements King {
static final String DESCRIPTION = "This is the Elven king!";
static final String DESCRIPTION = "This is the elven king!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfArmy implements Army {
static final String DESCRIPTION = "This is the Elven Army!";
static final String DESCRIPTION = "This is the elven Army!";
@Override
public String getDescription() {
return DESCRIPTION;
@ -77,7 +77,7 @@ public class ElfArmy implements Army {
```
Then we have the abstraction and implementations for the kingdom factory
Then we have the abstraction and implementations for the kingdom factory.
```java
public interface KingdomFactory {
@ -111,7 +111,7 @@ public class OrcKingdomFactory implements KingdomFactory {
}
```
Now we have our abstract factory that lets us make family of related objects i.e. Elven kingdom factory creates Elven castle, king and army etc.
Now we have the abstract factory that lets us make a family of related objects i.e. elven kingdom factory creates elven castle, king and army, etc.
```java
var factory = new ElfKingdomFactory();
@ -127,13 +127,13 @@ army.getDescription();
Program output:
```java
This is the Elven castle!
This is the Elven king!
This is the Elven Army!
This is the elven castle!
This is the elven king!
This is the elven Army!
```
Now, we can design a factory for our different kingdom factories. In this example, we created FactoryMaker, responsible for returning an instance of either ElfKingdomFactory or OrcKingdomFactory.
The client can use FactoryMaker to create the desired concrete factory which, in turn, will produce different concrete objects (Army, King, Castle).
Now, we can design a factory for our different kingdom factories. In this example, we created `FactoryMaker`, responsible for returning an instance of either `ElfKingdomFactory` or `OrcKingdomFactory`.
The client can use `FactoryMaker` to create the desired concrete factory which, in turn, will produce different concrete objects (derived from `Army`, `King`, `Castle`).
In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for.
```java
@ -179,8 +179,8 @@ public static void main(String[] args) {
Use the Abstract Factory pattern when
* The system should be independent of how its products are created, composed and represented
* The system should be configured with one of multiple families of products
* The system should be independent of how its products are created, composed, and represented
* The system should be configured with one of the multiple families of products
* The family of related product objects is designed to be used together, and you need to enforce this constraint
* You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations
* The lifetime of the dependency is conceptually shorter than the lifetime of the consumer.
@ -196,13 +196,13 @@ Example use cases
* Unit test case writing becomes much easier
* UI tools for different OS
## Consequences:
## Consequences
* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
* While the pattern is great when creating predefined objects, adding the new ones might be challenging.
* The code becomes more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.
* The code becomes more complicated than it should be since a lot of new interfaces and classes are introduced along with the pattern.
## Tutorial
## Tutorials
* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java)

View File

@ -37,7 +37,7 @@ import lombok.extern.slf4j.Slf4j;
*
* <p>The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory})
* and its implementations ( {@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses
* both concrete implementations to create a king, a castle and an army.
* both concrete implementations to create a king, a castle, and an army.
*/
@Slf4j
public class App implements Runnable {
@ -60,13 +60,13 @@ public class App implements Runnable {
@Override
public void run() {
LOGGER.info("Elf Kingdom");
LOGGER.info("elf kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
LOGGER.info("Orc Kingdom");
LOGGER.info("orc kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ORC);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class ElfArmy implements Army {
static final String DESCRIPTION = "This is the Elven Army!";
static final String DESCRIPTION = "This is the elven army!";
@Override
public String getDescription() {

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class ElfCastle implements Castle {
static final String DESCRIPTION = "This is the Elven castle!";
static final String DESCRIPTION = "This is the elven castle!";
@Override
public String getDescription() {

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class ElfKing implements King {
static final String DESCRIPTION = "This is the Elven king!";
static final String DESCRIPTION = "This is the elven king!";
@Override
public String getDescription() {

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class OrcArmy implements Army {
static final String DESCRIPTION = "This is the Orc Army!";
static final String DESCRIPTION = "This is the orc army!";
@Override
public String getDescription() {

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class OrcCastle implements Castle {
static final String DESCRIPTION = "This is the Orc castle!";
static final String DESCRIPTION = "This is the orc castle!";
@Override
public String getDescription() {

View File

@ -28,7 +28,7 @@ package com.iluwatar.abstractfactory;
*/
public class OrcKing implements King {
static final String DESCRIPTION = "This is the Orc king!";
static final String DESCRIPTION = "This is the orc king!";
@Override
public String getDescription() {

View File

@ -29,14 +29,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test for abstract factory.
* Tests for abstract factory.
*/
class AbstractFactoryTest {
private final App app = new App();
@Test
void king() {
void verifyKingCreation() {
app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
final var kingdom = app.getKingdom();
@ -51,7 +51,7 @@ class AbstractFactoryTest {
}
@Test
void castle() {
void verifyCastleCreation() {
app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
final var kingdom = app.getKingdom();
@ -66,7 +66,7 @@ class AbstractFactoryTest {
}
@Test
void army() {
void verifyArmyCreation() {
app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
final var kingdom = app.getKingdom();
@ -81,7 +81,7 @@ class AbstractFactoryTest {
}
@Test
void createElfKingdom() {
void verifyElfKingdomCreation() {
app.createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
final var kingdom = app.getKingdom();
@ -97,7 +97,7 @@ class AbstractFactoryTest {
}
@Test
void createOrcKingdom() {
void verifyOrcKingdomCreation() {
app.createKingdom(Kingdom.FactoryMaker.KingdomType.ORC);
final var kingdom = app.getKingdom();

View File

@ -28,10 +28,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
* Check whether the execution of the main method in {@link App} throws an exception.
*/
class AppTest {

View File

@ -11,7 +11,7 @@ tags:
## Intent
The active object design pattern decouples method execution from method invocation for objects that each reside in their thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.
The active object design pattern decouples method execution from method invocation for objects that each reside in their thread of control. The goal is to introduce concurrency, by using asynchronous method invocation, and a scheduler for handling requests.
## Explanation
@ -70,7 +70,7 @@ public abstract class ActiveCreature{
requests.put(new Runnable() {
@Override
public void run() {
logger.info("{} has started to roam and the wastelands.",name());
logger.info("{} has started to roam the wastelands.",name());
}
}
);
@ -82,7 +82,7 @@ public abstract class ActiveCreature{
}
```
We can see that any class that will extend the ActiveCreature class will have its own thread of control to execute and invocate methods.
We can see that any class that will extend the ActiveCreature class will have its own thread of control to invoke and execute methods.
For example, the Orc class:
@ -96,7 +96,7 @@ public class Orc extends ActiveCreature {
}
```
Now, we can create multiple creatures such as Orcs, tell them to eat and roam and they will execute it on their own thread of control:
Now, we can create multiple creatures such as Orcs, tell them to eat and roam, and they will execute it on their own thread of control:
```java
public static void main(String[] args) {
@ -123,4 +123,4 @@ Now, we can create multiple creatures such as Orcs, tell them to eat and roam an
## Class diagram
![alt text](./etc/active-object.urm.PNG "Active Object class diagram")
![alt text](./etc/active-object.urm.png "Active Object class diagram")

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -82,7 +82,7 @@ public abstract class ActiveCreature {
}
/**
* Roam in the wastelands.
* Roam the wastelands.
* @throws InterruptedException due to firing a new Runnable.
*/
public void roam() throws InterruptedException {

View File

@ -105,7 +105,7 @@ Use the Adapter pattern when
* you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.
* most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
## Consequences:
## Consequences
Class and object adapters have different trade-offs. A class adapter
* adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter wont work when we want to adapt a class and all its subclasses.
@ -118,7 +118,7 @@ An object adapter
* makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself.
## Real world examples
## Known uses
* [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29)
* [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-)

View File

@ -48,7 +48,7 @@ class AggregatorTest {
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
MockitoAnnotations.openMocks(this);
}
/**

View File

@ -48,7 +48,7 @@ class ApiGatewayTest {
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
MockitoAnnotations.openMocks(this);
}
/**

View File

@ -68,7 +68,7 @@ class ThreadAsyncExecutorTest {
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
MockitoAnnotations.openMocks(this);
}
/**

View File

@ -19,7 +19,7 @@ Decouple an abstraction from its implementation so that the two can vary indepen
## Explanation
Real world example
Real-world example
> Consider you have a weapon with different enchantments, and you are supposed to allow mixing
> different weapons with different enchantments. What would you do? Create multiple copies of each
@ -161,27 +161,36 @@ public class SoulEatingEnchantment implements Enchantment {
Here are both hierarchies in action:
```java
LOGGER.info("The knight receives an enchanted sword.");
var enchantedSword = new Sword(new SoulEatingEnchantment());
enchantedSword.wield();
enchantedSword.swing();
enchantedSword.unwield();
// The sword is wielded.
// The item spreads bloodlust.
// The sword is swinged.
// The item eats the soul of enemies.
// The sword is unwielded.
// Bloodlust slowly disappears.
LOGGER.info("The valkyrie receives an enchanted hammer.");
var hammer = new Hammer(new FlyingEnchantment());
hammer.wield();
hammer.swing();
hammer.unwield();
// The hammer is wielded.
// The item begins to glow faintly.
// The hammer is swinged.
// The item flies and strikes the enemies finally returning to owner's hand.
// The hammer is unwielded.
// The item's glow fades.
```
Here's the console output.
```
The knight receives an enchanted sword.
The sword is wielded.
The item spreads bloodlust.
The sword is swung.
The item eats the soul of enemies.
The sword is unwielded.
Bloodlust slowly disappears.
The valkyrie receives an enchanted hammer.
The hammer is wielded.
The item begins to glow faintly.
The hammer is swung.
The item flies and strikes the enemies finally returning to owner's hand.
The hammer is unwielded.
The item's glow fades.
```
## Class diagram

View File

@ -43,7 +43,7 @@ public class Hammer implements Weapon {
@Override
public void swing() {
LOGGER.info("The hammer is swinged.");
LOGGER.info("The hammer is swung.");
enchantment.apply();
}

View File

@ -43,7 +43,7 @@ public class Sword implements Weapon {
@Override
public void swing() {
LOGGER.info("The sword is swinged.");
LOGGER.info("The sword is swung.");
enchantment.apply();
}

View File

@ -16,11 +16,11 @@ process can create different representations.
## Explanation
Real world example
Real-world example
> Imagine a character generator for a role-playing game. The easiest option is to let the computer
> create the character for you. If you want to manually select the character details like
> profession, gender, hair color etc. the character generation becomes a step-by-step process that
> profession, gender, hair color, etc. the character generation becomes a step-by-step process that
> completes when all the selections are ready.
In plain words
@ -49,7 +49,7 @@ anti-pattern.
**Programmatic Example**
The sane alternative is to use the Builder pattern. First of all we have our hero that we want to
The sane alternative is to use the Builder pattern. First of all, we have our hero that we want to
create:
```java
@ -134,7 +134,7 @@ Use the Builder pattern when
* The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled
* The construction process must allow different representations for the object that's constructed
## Real world examples
## Known uses
* [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
* [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) as well as similar buffers such as FloatBuffer, IntBuffer and so on.

View File

@ -1,8 +1,8 @@
---
layout: pattern
title: Chain of responsibility
folder: chain
permalink: /patterns/chain/
folder: chain-of-responsibility
permalink: /patterns/chain-of-responsibility/
categories: Behavioral
language: en
tags:
@ -10,16 +10,17 @@ tags:
---
## Intent
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to
handle the request. Chain the receiving objects and pass the request along the chain until an object
handles it.
## Explanation
Real world example
Real-world example
> The Orc King gives loud orders to his army. The closest one to react is the commander, then
> officer and then soldier. The commander, officer and soldier here form a chain of responsibility.
> an officer, and then a soldier. The commander, officer, and soldier form a chain of responsibility.
In plain words
@ -35,7 +36,7 @@ Wikipedia says
**Programmatic Example**
Translating our example with the orcs from above. First we have the `Request` class:
Translating our example with the orcs from above. First, we have the `Request` class:
```java
public class Request {
@ -66,7 +67,7 @@ public enum RequestType {
}
```
Then the request handler hierarchy
Next, we show the request handler hierarchy.
```java
@Slf4j
@ -116,7 +117,7 @@ public class OrcCommander extends RequestHandler {
```
Then we have the Orc King who gives the orders and forms the chain
The Orc King gives the orders and forms the chain.
```java
public class OrcKing {
@ -136,18 +137,26 @@ public class OrcKing {
}
```
Then it is used as follows
The chain of responsibility in action.
```java
var king = new OrcKing();
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); // Orc commander handling request "defend castle"
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); // Orc officer handling request "torture prisoner"
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); // Orc soldier handling request "collect tax"
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle"));
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner"));
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
```
The console output.
```
Orc commander handling request "defend castle"
Orc officer handling request "torture prisoner"
Orc soldier handling request "collect tax"
```
## Class diagram
![alt text](./etc/chain.urm.png "Chain of Responsibility class diagram")
![alt text](./etc/chain-of-responsibility.urm.png "Chain of Responsibility class diagram")
## Applicability
@ -157,7 +166,7 @@ Use Chain of Responsibility when
* You want to issue a request to one of several objects without specifying the receiver explicitly.
* The set of objects that can handle a request should be specified dynamically.
## Real world examples
## Known uses
* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29)
* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html)

View File

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 59 KiB

View File

@ -31,7 +31,7 @@
<artifactId>java-design-patterns</artifactId>
<version>1.25.0-SNAPSHOT</version>
</parent>
<artifactId>chain</artifactId>
<artifactId>chain-of-responsibility</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>

View File

@ -19,7 +19,7 @@ Encapsulate a request as an object, thereby letting you parameterize clients wit
requests, queue or log requests, and support undoable operations.
## Explanation
Real world example
Real-world example
> There is a wizard casting spells on a goblin. The spells are executed on the goblin one by one.
> The first spell shrinks the goblin and the second makes him invisible. Then the wizard reverses
@ -135,7 +135,7 @@ public class Goblin extends Target {
}
```
Finally we have the wizard in main function who casts spell
Finally, we have the wizard in the main function casting spells.
```java
public static void main(String[] args) {
@ -202,32 +202,29 @@ Use the Command pattern when you want to:
* Parameterize objects by an action to perform. You can express such parameterization in a
procedural language with a callback function, that is, a function that's registered somewhere to be
called at a later point. Commands are an object-oriented replacement for callbacks.
* Specify, queue, and execute requests at different times. A Command object can have a lifetime
* Specify, queue, and execute requests at different times. A Command object can have a life
independent of the original request. If the receiver of a request can be represented in an address
space-independent way, then you can transfer a command object for the request to a different process
and fulfill the request there.
* Support undo. The Command's execute operation can store state for reversing its effects in the
command itself. The Command interface must have an added un-execute operation that reverses the
effects of a previous call to execute. The executed commands are stored in a history list.
Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling
un-execute and execute, respectively.
Unlimited-level undo and redo functionality is achieved by traversing this list backward and forward
calling un-execute and execute, respectively.
* Support logging changes so that they can be reapplied in case of a system crash. By augmenting the
Command interface with load and store operations, you can keep a persistent log of changes.
Recovering from a crash involves reloading logged commands from disk and re-executing them with
Recovering from a crash involves reloading logged commands from the disk and re-executing them with
the execute operation.
* Structure a system around high-level operations build on primitive operations. Such a structure is
common in information systems that support transactions. A transaction encapsulates a set of changes
to data. The Command pattern offers a way to model transactions. Commands have a common interface,
common in information systems that support transactions. A transaction encapsulates a set of data
changes. The Command pattern offers a way to model transactions. Commands have a common interface,
letting you invoke all transactions the same way. The pattern also makes it easy to extend the
system with new transactions.
* Keep a history of requests.
* Implement callback functionality.
* Implement the undo functionality.
## Typical Use Case
* To keep a history of requests
* Implement callback functionality
* Implement the undo functionality
## Real world examples
## Known uses
* [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)
* [org.junit.runners.model.Statement](https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/model/Statement.java)

View File

@ -26,7 +26,7 @@ package com.iluwatar.command;
/**
* The Command pattern is a behavioral design pattern in which an object is used to encapsulate all
* information needed to perform an action or trigger an event at a later time. This information
* includes the method name, the object that owns the method and values for the method parameters.
* includes the method name, the object that owns the method, and values for the method parameters.
*
* <p>Four terms always associated with the command pattern are command, receiver, invoker and
* client. A command object (spell) knows about the receiver (target) and invokes a method of the

View File

@ -25,4 +25,4 @@ We need a mechanism in place which can handle these kinds of situations. We have
## Credits
* [https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/]
* [Distributed Transactions: The Icebergs of Microservices](https://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/)

View File

@ -16,15 +16,15 @@ treat individual objects and compositions of objects uniformly.
## Explanation
Real world example
Real-world example
> Every sentence is composed of words which are in turn composed of characters. Each of these
> objects is printable and they can have something printed before or after them like sentence always
> ends with full stop and word always has space before it.
> objects are printable and they can have something printed before or after them like sentence
> always ends with full stop and word always has space before it.
In plain words
> Composite pattern lets clients treat the individual objects in a uniform manner.
> Composite pattern lets clients uniformly treat the individual objects.
Wikipedia says
@ -154,10 +154,22 @@ public class Messenger {
And then it can be used as:
```java
var orcMessage = new Messenger().messageFromOrcs();
orcMessage.print(); // Where there is a whip there is a way.
var elfMessage = new Messenger().messageFromElves();
elfMessage.print(); // Much wind pours from your mouth.
var messenger = new Messenger();
LOGGER.info("Message from the orcs: ");
messenger.messageFromOrcs().print();
LOGGER.info("Message from the elves: ");
messenger.messageFromElves().print();
```
The console output:
```
Message from the orcs:
Where there is a whip there is a way.
Message from the elves:
Much wind pours from your mouth.
```
## Class diagram
@ -172,7 +184,7 @@ Use the Composite pattern when
* You want clients to be able to ignore the difference between compositions of objects and
individual objects. Clients will treat all objects in the composite structure uniformly.
## Real world examples
## Known uses
* [java.awt.Container](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html) and [java.awt.Component](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html)
* [Apache Wicket](https://github.com/apache/wicket) component tree, see [Component](https://github.com/apache/wicket/blob/91e154702ab1ff3481ef6cbb04c6044814b7e130/wicket-core/src/main/java/org/apache/wicket/Component.java) and [MarkupContainer](https://github.com/apache/wicket/blob/b60ec64d0b50a611a9549809c9ab216f0ffa3ae3/wicket-core/src/main/java/org/apache/wicket/MarkupContainer.java)

View File

@ -45,14 +45,13 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
var messenger = new Messenger();
LOGGER.info("Message from the orcs: ");
messenger.messageFromOrcs().print();
var orcMessage = new Messenger().messageFromOrcs();
orcMessage.print();
LOGGER.info("\nMessage from the elves: ");
var elfMessage = new Messenger().messageFromElves();
elfMessage.print();
LOGGER.info("Message from the elves: ");
messenger.messageFromElves().print();
}
}

View File

@ -39,6 +39,6 @@ public class Sentence extends LetterComposite {
@Override
protected void printThisAfter() {
System.out.print(".");
System.out.print(".\n");
}
}

View File

@ -3,7 +3,6 @@ layout: pattern
title: Data Bus
folder: data-bus
permalink: /patterns/data-bus/
categories: Architectural
language: en
tags:

View File

@ -46,7 +46,7 @@ class DataBusTest {
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
MockitoAnnotations.openMocks(this);
}
@Test

View File

@ -6,7 +6,7 @@ permalink: /patterns/decorator/
categories: Structural
language: en
tags:
- Gang Of Four
- Gang of Four
- Extensibility
---
@ -21,9 +21,9 @@ alternative to subclassing for extending functionality.
## Explanation
Real world example
Real-world example
> There is an angry troll living in the nearby hills. Usually it goes bare handed but sometimes it
> There is an angry troll living in the nearby hills. Usually, it goes bare-handed but sometimes it
> has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it
> dynamically with a suitable weapon.
@ -72,7 +72,7 @@ public class SimpleTroll implements Troll {
}
```
Next we want to add club for the troll. We can do it dynamically by using a decorator:
Next, we want to add a club for the troll. We can do it dynamically by using a decorator:
```java
@Slf4j
@ -106,23 +106,33 @@ Here's the troll in action:
```java
// simple troll
LOGGER.info("A simple looking troll approaches.");
var troll = new SimpleTroll();
troll.attack(); // The troll tries to grab you!
troll.fleeBattle(); // The troll shrieks in horror and runs away!
troll.attack();
troll.fleeBattle();
LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you.");
var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack(); // The troll tries to grab you! The troll swings at you with a club!
clubbedTroll.fleeBattle(); // The troll shrieks in horror and runs away!
clubbedTroll.attack();
clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower());
```
Program output:
```java
A simple looking troll approaches.
The troll tries to grab you!
The troll shrieks in horror and runs away!
The troll tries to grab you! The troll swings at you with a club!
Simple troll power: 10.
A troll with huge club surprises you.
The troll tries to grab you!
The troll swings at you with a club!
The troll shrieks in horror and runs away!
Clubbed troll power: 20.
```
## Class diagram
@ -140,11 +150,11 @@ affecting other objects.
are possible and would produce an explosion of subclasses to support every combination. Or a class
definition may be hidden or otherwise unavailable for subclassing.
## Tutorial
## Tutorials
* [Decorator Pattern Tutorial](https://www.journaldev.com/1540/decorator-design-pattern-in-java-example)
## Real world examples
## Known uses
* [java.io.InputStream](http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html), [java.io.OutputStream](http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html),
[java.io.Reader](http://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) and [java.io.Writer](http://docs.oracle.com/javase/8/docs/api/java/io/Writer.html)

View File

@ -50,13 +50,13 @@ public class App {
var troll = new SimpleTroll();
troll.attack();
troll.fleeBattle();
LOGGER.info("Simple troll power {}.\n", troll.getAttackPower());
LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you.");
var clubbedTroll = new ClubbedTroll(troll);
clubbedTroll.attack();
clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power {}.\n", clubbedTroll.getAttackPower());
LOGGER.info("Clubbed troll power: {}.\n", clubbedTroll.getAttackPower());
}
}

View File

@ -103,4 +103,4 @@ Use the Dependency Injection pattern when:
* [Dependency Injection Principles, Practices, and Patterns](https://www.amazon.com/gp/product/161729473X/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=161729473X&linkId=57079257a5c7d33755493802f3b884bd)
* [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/gp/product/0132350882/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0132350882&linkCode=as2&tag=javadesignpat-20&linkId=2c390d89cc9e61c01b9e7005c7842871)
* [Java 9 Dependency Injection: Write loosely coupled code with Spring 5 and Guice](https://www.amazon.com/gp/product/1788296257/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=1788296257&linkId=4e9137a3bf722a8b5b156cce1eec0fc1)
* [Google Guice Tutorial: Open source Java based dependency injection framework](https://www.amazon.com/gp/product/B083P7DZ8M/ref=as_li_tl?ie=UTF8&tag=javadesignpat-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=B083P7DZ8M&linkId=04f0f902c877921e45215b624a124bfe)
* [Google Guice: Agile Lightweight Dependency Injection Framework](https://www.amazon.com/gp/product/1590599977/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1590599977&linkId=3b10c90b7ba480a1b7777ff38000f956)

326
domain-model/README.md Normal file
View File

@ -0,0 +1,326 @@
---
layout: pattern
title: Domain Model
folder: domain-model
permalink: /patterns/domain-model/
categories: Architectural
language: en
tags:
- Domain
---
## Intent
Domain model pattern provides an object-oriented way of dealing with complicated logic. Instead of having one procedure that handles all business logic for a user action there are multiple objects and each of them handles a slice of domain logic that is relevant to it.
## Explanation
Real world example
> Let's assume that we need to build an e-commerce web application. While analyzing requirements you will notice that there are few nouns you talk about repeatedly. Its your Customer, and a Product the customer looks for. These two are your domain-specific classes and each of that classes will include some business logic specific to its domain.
In plain words
> The Domain Model is an object model of the domain that incorporates both behavior and data.
Programmatic Example
In the example of the e-commerce app, we need to deal with the domain logic of customers who want to buy products and return them if they want. We can use the domain model pattern and create classes `Customer` and `Product` where every single instance of that class incorporates both behavior and data and represents only one record in the underlying table.
Here is the `Product` domain class with fields `name`, `price`, `expirationDate` which is specific for each product, `productDao` for working with DB, `save` method for saving product and `getSalePrice` method which return price for this product with discount.
```java
@Slf4j
@Getter
@Setter
@Builder
@AllArgsConstructor
public class Product {
private static final int DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE = 4;
private static final double DISCOUNT_RATE = 0.2;
@NonNull private final ProductDao productDao;
@NonNull private String name;
@NonNull private Money price;
@NonNull private LocalDate expirationDate;
/**
* Save product or update if product already exist.
*/
public void save() {
try {
Optional<Product> product = productDao.findByName(name);
if (product.isPresent()) {
productDao.update(this);
} else {
productDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
}
/**
* Calculate sale price of product with discount.
*/
public Money getSalePrice() {
return price.minus(calculateDiscount());
}
private Money calculateDiscount() {
if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate)
< DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) {
return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN);
}
return Money.zero(USD);
}
}
```
Here is the `Customer` domain class with fields `name`, `money` which is specific for each customer, `customerDao` for working with DB, `save` for saving customer, `buyProduct` which add a product to purchases and withdraw money, `returnProduct` which remove product from purchases and return money, `showPurchases` and `showBalance` methods for printing customer's purchases and money balance.
```java
@Slf4j
@Getter
@Setter
@Builder
public class Customer {
@NonNull private final CustomerDao customerDao;
@Builder.Default private List<Product> purchases = new ArrayList<>();
@NonNull private String name;
@NonNull private Money money;
/**
* Save customer or update if customer already exist.
*/
public void save() {
try {
Optional<Customer> customer = customerDao.findByName(name);
if (customer.isPresent()) {
customerDao.update(this);
} else {
customerDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
}
/**
* Add product to purchases, save to db and withdraw money.
*
* @param product to buy.
*/
public void buyProduct(Product product) {
LOGGER.info(
String.format(
"%s want to buy %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
try {
withdraw(product.getSalePrice());
} catch (IllegalArgumentException ex) {
LOGGER.error(ex.getMessage());
return;
}
try {
customerDao.addProduct(product, this);
purchases.add(product);
LOGGER.info(String.format("%s bought %s!", name, product.getName()));
} catch (SQLException exception) {
receiveMoney(product.getSalePrice());
LOGGER.error(exception.getMessage());
}
}
/**
* Remove product from purchases, delete from db and return money.
*
* @param product to return.
*/
public void returnProduct(Product product) {
LOGGER.info(
String.format(
"%s want to return %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
if (purchases.contains(product)) {
try {
customerDao.deleteProduct(product, this);
purchases.remove(product);
receiveMoney(product.getSalePrice());
LOGGER.info(String.format("%s returned %s!", name, product.getName()));
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
} else {
LOGGER.error(String.format("%s didn't buy %s...", name, product.getName()));
}
}
/**
* Print customer's purchases.
*/
public void showPurchases() {
Optional<String> purchasesToShow =
purchases.stream()
.map(p -> p.getName() + " - $" + p.getSalePrice().getAmount())
.reduce((p1, p2) -> p1 + ", " + p2);
if (purchasesToShow.isPresent()) {
LOGGER.info(name + " bought: " + purchasesToShow.get());
} else {
LOGGER.info(name + " didn't bought anything");
}
}
/**
* Print customer's money balance.
*/
public void showBalance() {
LOGGER.info(name + " balance: " + money);
}
private void withdraw(Money amount) throws IllegalArgumentException {
if (money.compareTo(amount) < 0) {
throw new IllegalArgumentException("Not enough money!");
}
money = money.minus(amount);
}
private void receiveMoney(Money amount) {
money = money.plus(amount);
}
}
```
In the class `App`, we create a new instance of class Customer which represents customer Tom and handle data and actions of that customer and creating three products that Tom wants to buy.
```java
// Create data source and create the customers, products and purchases tables
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// create customer
var customerDao = new CustomerDaoImpl(dataSource);
var tom =
Customer.builder()
.name("Tom")
.money(Money.of(USD, 30))
.customerDao(customerDao)
.build();
tom.save();
// create products
var productDao = new ProductDaoImpl(dataSource);
var eggs =
Product.builder()
.name("Eggs")
.price(Money.of(USD, 10.0))
.expirationDate(LocalDate.now().plusDays(7))
.productDao(productDao)
.build();
var butter =
Product.builder()
.name("Butter")
.price(Money.of(USD, 20.00))
.expirationDate(LocalDate.now().plusDays(9))
.productDao(productDao)
.build();
var cheese =
Product.builder()
.name("Cheese")
.price(Money.of(USD, 25.0))
.expirationDate(LocalDate.now().plusDays(2))
.productDao(productDao)
.build();
eggs.save();
butter.save();
cheese.save();
// show money balance of customer after each purchase
tom.showBalance();
tom.showPurchases();
// buy eggs
tom.buyProduct(eggs);
tom.showBalance();
// buy butter
tom.buyProduct(butter);
tom.showBalance();
// trying to buy cheese, but receive a refusal
// because he didn't have enough money
tom.buyProduct(cheese);
tom.showBalance();
// return butter and get money back
tom.returnProduct(butter);
tom.showBalance();
// Tom can buy cheese now because he has enough money
// and there is a discount on cheese because it expires in 2 days
tom.buyProduct(cheese);
tom.save();
// show money balance and purchases after shopping
tom.showBalance();
tom.showPurchases();
```
The program output:
```java
17:52:28.690 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 30.00
17:52:28.695 [main] INFO com.iluwatar.domainmodel.Customer - Tom didn't bought anything
17:52:28.699 [main] INFO com.iluwatar.domainmodel.Customer - Tom want to buy Eggs($10.00)...
17:52:28.705 [main] INFO com.iluwatar.domainmodel.Customer - Tom bought Eggs!
17:52:28.705 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 20.00
17:52:28.705 [main] INFO com.iluwatar.domainmodel.Customer - Tom want to buy Butter($20.00)...
17:52:28.712 [main] INFO com.iluwatar.domainmodel.Customer - Tom bought Butter!
17:52:28.712 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 0.00
17:52:28.712 [main] INFO com.iluwatar.domainmodel.Customer - Tom want to buy Cheese($20.00)...
17:52:28.712 [main] ERROR com.iluwatar.domainmodel.Customer - Not enough money!
17:52:28.712 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 0.00
17:52:28.712 [main] INFO com.iluwatar.domainmodel.Customer - Tom want to return Butter($20.00)...
17:52:28.721 [main] INFO com.iluwatar.domainmodel.Customer - Tom returned Butter!
17:52:28.721 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 20.00
17:52:28.721 [main] INFO com.iluwatar.domainmodel.Customer - Tom want to buy Cheese($20.00)...
17:52:28.726 [main] INFO com.iluwatar.domainmodel.Customer - Tom bought Cheese!
17:52:28.737 [main] INFO com.iluwatar.domainmodel.Customer - Tom balance: USD 0.00
17:52:28.738 [main] INFO com.iluwatar.domainmodel.Customer - Tom bought: Eggs - $10.00, Cheese - $20.00
```
## Class diagram
![](./etc/domain-model.urm.png "domain model")
## Applicability
Use a Domain model pattern when your domain logic is complex and that complexity can rapidly grow because this pattern handles increasing complexity very well. Otherwise, it's a more complex solution for organizing domain logic, so shouldn't use Domain Model pattern for systems with simple domain logic, because the cost of understanding it and complexity of data source exceeds the benefit of this pattern.
## Related patterns
- [Transaction Script](https://java-design-patterns.com/patterns/transaction-script/)
- [Table Module](https://java-design-patterns.com/patterns/table-module/)
- [Service Layer](https://java-design-patterns.com/patterns/service-layer/)
## Credits
* [Domain Model Pattern](https://martinfowler.com/eaaCatalog/domainModel.html)
* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321127420&linkId=18acc13ba60d66690009505577c45c04)
* [Architecture patterns: domain model and friends](https://inviqa.com/blog/architecture-patterns-domain-model-and-friends)

Binary file not shown.

After

Width:  |  Height:  |  Size: 314 KiB

View File

@ -0,0 +1,87 @@
@startuml
package com.iluwatar.domainmodel {
class App {
+ CREATE_SCHEMA_SQL : String {static}
+ DELETE_SCHEMA_SQL : String {static}
+ H2_DB_URL : String {static}
+ App()
- createDataSource() : DataSource {static}
- createSchema(dataSource : DataSource) {static}
- deleteSchema(dataSource : DataSource) {static}
+ main(args : String[]) {static}
}
class Customer {
- customerDao : CustomerDao
- money : Money
- name : String
- purchases : List<Product>
~ Customer(customerDao : CustomerDao, purchases : List<Product>, name : String, money : Money)
+ builder() : CustomerBuilder {static}
+ buyProduct(product : Product)
+ getCustomerDao() : CustomerDao
+ getMoney() : Money
+ getName() : String
+ getPurchases() : List<Product>
- receiveMoney(amount : Money)
+ returnProduct(product : Product)
+ save()
+ setMoney(money : Money)
+ setName(name : String)
+ setPurchases(purchases : List<Product>)
+ showBalance()
+ showPurchases()
- withdraw(amount : Money)
}
interface CustomerDao {
+ addProduct(Product, Customer) {abstract}
+ deleteProduct(Product, Customer) {abstract}
+ findByName(String) : Optional<Customer> {abstract}
+ save(Customer) {abstract}
+ update(Customer) {abstract}
}
class CustomerDaoImpl {
- dataSource : DataSource
+ CustomerDaoImpl(userDataSource : DataSource)
+ addProduct(product : Product, customer : Customer)
+ deleteProduct(product : Product, customer : Customer)
+ findByName(name : String) : Optional<Customer>
+ save(customer : Customer)
+ update(customer : Customer)
}
class Product {
- expirationDate : LocalDate
- name : String
- price : Money
- productDao : ProductDao
+ Product(productDao : ProductDao, name : String, price : Money, expirationDate : LocalDate)
+ builder() : ProductBuilder {static}
- calculateDiscount() : Money
+ getExpirationDate() : LocalDate
+ getName() : String
+ getPrice() : Money
+ getProductDao() : ProductDao
+ getSalePrice() : Money
+ save()
+ setExpirationDate(expirationDate : LocalDate)
+ setName(name : String)
+ setPrice(price : Money)
}
interface ProductDao {
+ findByName(String) : Optional<Product> {abstract}
+ save(Product) {abstract}
+ update(Product) {abstract}
}
class ProductDaoImpl {
- dataSource : DataSource
+ ProductDaoImpl(userDataSource : DataSource)
+ findByName(name : String) : Optional<Product>
+ save(product : Product)
+ update(product : Product)
}
}
Product --> ProductDao
Customer --> CustomerDao
Customer --> Product
CustomerDaoImpl ..|> CustomerDao
ProductDaoImpl ..|> ProductDao
@enduml

78
domain-model/pom.xml Normal file
View File

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Copyright © 2014-2021 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">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.25.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>domain-model</artifactId>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-money</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.domainmodel.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,173 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import static org.joda.money.CurrencyUnit.USD;
import java.sql.SQLException;
import java.time.LocalDate;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.joda.money.Money;
/**
* Domain Model pattern is a more complex solution for organizing domain logic than Transaction
* Script and Table Module. It provides an object-oriented way of dealing with complicated logic.
* Instead of having one procedure that handles all business logic for a user action like
* Transaction Script there are multiple objects and each of them handles a slice of domain logic
* that is relevant to it. The significant difference between Domain Model and Table Module pattern
* is that in Table Module a single class encapsulates all the domain logic for all records stored
* in table when in Domain Model every single class represents only one record in underlying table.
*
* <p>In this example, we will use the Domain Model pattern to implement buying of products
* by customers in a Shop. The main method will create a customer and a few products.
* Customer will do a few purchases, try to buy product which are too expensive for him,
* return product which he bought to return money.</p>
*/
public class App {
public static final String H2_DB_URL = "jdbc:h2:~/test";
public static final String CREATE_SCHEMA_SQL =
"CREATE TABLE CUSTOMERS (name varchar primary key, money decimal);"
+ "CREATE TABLE PRODUCTS (name varchar primary key, price decimal, expiration_date date);"
+ "CREATE TABLE PURCHASES ("
+ "product_name varchar references PRODUCTS(name),"
+ "customer_name varchar references CUSTOMERS(name));";
public static final String DELETE_SCHEMA_SQL =
"DROP TABLE CUSTOMERS IF EXISTS;"
+ "DROP TABLE PURCHASES IF EXISTS;"
+ "DROP TABLE PRODUCTS IF EXISTS;";
/**
* Program entry point.
*
* @param args command line arguments
* @throws Exception if any error occurs
*/
public static void main(String[] args) throws Exception {
// Create data source and create the customers, products and purchases tables
final var dataSource = createDataSource();
deleteSchema(dataSource);
createSchema(dataSource);
// create customer
var customerDao = new CustomerDaoImpl(dataSource);
var tom =
Customer.builder()
.name("Tom")
.money(Money.of(USD, 30))
.customerDao(customerDao)
.build();
tom.save();
// create products
var productDao = new ProductDaoImpl(dataSource);
var eggs =
Product.builder()
.name("Eggs")
.price(Money.of(USD, 10.0))
.expirationDate(LocalDate.now().plusDays(7))
.productDao(productDao)
.build();
var butter =
Product.builder()
.name("Butter")
.price(Money.of(USD, 20.00))
.expirationDate(LocalDate.now().plusDays(9))
.productDao(productDao)
.build();
var cheese =
Product.builder()
.name("Cheese")
.price(Money.of(USD, 25.0))
.expirationDate(LocalDate.now().plusDays(2))
.productDao(productDao)
.build();
eggs.save();
butter.save();
cheese.save();
// show money balance of customer after each purchase
tom.showBalance();
tom.showPurchases();
// buy eggs
tom.buyProduct(eggs);
tom.showBalance();
// buy butter
tom.buyProduct(butter);
tom.showBalance();
// trying to buy cheese, but receive a refusal
// because he didn't have enough money
tom.buyProduct(cheese);
tom.showBalance();
// return butter and get money back
tom.returnProduct(butter);
tom.showBalance();
// Tom can buy cheese now because he has enough money
// and there is a discount on cheese because it expires in 2 days
tom.buyProduct(cheese);
tom.save();
// show money balance and purchases after shopping
tom.showBalance();
tom.showPurchases();
}
private static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setUrl(H2_DB_URL);
return dataSource;
}
private static void deleteSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(DELETE_SCHEMA_SQL);
}
}
private static void createSchema(DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.execute(CREATE_SCHEMA_SQL);
}
}
}

View File

@ -0,0 +1,153 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.Money;
/**
* This class organizes domain logic of customer.
* A single instance of this class
* contains both the data and behavior of a single customer.
*/
@Slf4j
@Getter
@Setter
@Builder
public class Customer {
@NonNull private final CustomerDao customerDao;
@Builder.Default private List<Product> purchases = new ArrayList<>();
@NonNull private String name;
@NonNull private Money money;
/**
* Save customer or update if customer already exist.
*/
public void save() {
try {
Optional<Customer> customer = customerDao.findByName(name);
if (customer.isPresent()) {
customerDao.update(this);
} else {
customerDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
}
/**
* Add product to purchases, save to db and withdraw money.
*
* @param product to buy.
*/
public void buyProduct(Product product) {
LOGGER.info(
String.format(
"%s want to buy %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
try {
withdraw(product.getSalePrice());
} catch (IllegalArgumentException ex) {
LOGGER.error(ex.getMessage());
return;
}
try {
customerDao.addProduct(product, this);
purchases.add(product);
LOGGER.info(String.format("%s bought %s!", name, product.getName()));
} catch (SQLException exception) {
receiveMoney(product.getSalePrice());
LOGGER.error(exception.getMessage());
}
}
/**
* Remove product from purchases, delete from db and return money.
*
* @param product to return.
*/
public void returnProduct(Product product) {
LOGGER.info(
String.format(
"%s want to return %s($%.2f)...",
name, product.getName(), product.getSalePrice().getAmount()));
if (purchases.contains(product)) {
try {
customerDao.deleteProduct(product, this);
purchases.remove(product);
receiveMoney(product.getSalePrice());
LOGGER.info(String.format("%s returned %s!", name, product.getName()));
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
} else {
LOGGER.error(String.format("%s didn't buy %s...", name, product.getName()));
}
}
/**
* Print customer's purchases.
*/
public void showPurchases() {
Optional<String> purchasesToShow =
purchases.stream()
.map(p -> p.getName() + " - $" + p.getSalePrice().getAmount())
.reduce((p1, p2) -> p1 + ", " + p2);
if (purchasesToShow.isPresent()) {
LOGGER.info(name + " bought: " + purchasesToShow.get());
} else {
LOGGER.info(name + " didn't bought anything");
}
}
/**
* Print customer's money balance.
*/
public void showBalance() {
LOGGER.info(name + " balance: " + money);
}
private void withdraw(Money amount) throws IllegalArgumentException {
if (money.compareTo(amount) < 0) {
throw new IllegalArgumentException("Not enough money!");
}
money = money.minus(amount);
}
private void receiveMoney(Money amount) {
money = money.plus(amount);
}
}

View File

@ -0,0 +1,40 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import java.sql.SQLException;
import java.util.Optional;
public interface CustomerDao {
Optional<Customer> findByName(String name) throws SQLException;
void update(Customer customer) throws SQLException;
void save(Customer customer) throws SQLException;
void addProduct(Product product, Customer customer) throws SQLException;
void deleteProduct(Product product, Customer customer) throws SQLException;
}

View File

@ -0,0 +1,109 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import static org.joda.money.CurrencyUnit.USD;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import javax.sql.DataSource;
import org.joda.money.Money;
public class CustomerDaoImpl implements CustomerDao {
private final DataSource dataSource;
public CustomerDaoImpl(final DataSource userDataSource) {
this.dataSource = userDataSource;
}
@Override
public Optional<Customer> findByName(String name) throws SQLException {
var sql = "select * from CUSTOMERS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
return Optional.of(
Customer.builder()
.name(rs.getString("name"))
.money(Money.of(USD, rs.getBigDecimal("money")))
.customerDao(this)
.build());
} else {
return Optional.empty();
}
}
}
@Override
public void update(Customer customer) throws SQLException {
var sql = "update CUSTOMERS set money = ? where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setBigDecimal(1, customer.getMoney().getAmount());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
}
@Override
public void save(Customer customer) throws SQLException {
var sql = "insert into CUSTOMERS (name, money) values (?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, customer.getName());
preparedStatement.setBigDecimal(2, customer.getMoney().getAmount());
preparedStatement.executeUpdate();
}
}
@Override
public void addProduct(Product product, Customer customer) throws SQLException {
var sql = "insert into PURCHASES (product_name, customer_name) values (?,?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
}
@Override
public void deleteProduct(Product product, Customer customer) throws SQLException {
var sql = "delete from PURCHASES where product_name = ? and customer_name = ?";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setString(2, customer.getName());
preparedStatement.executeUpdate();
}
}
}

View File

@ -0,0 +1,94 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import static org.joda.money.CurrencyUnit.USD;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.Money;
/**
* This class organizes domain logic of product.
* A single instance of this class
* contains both the data and behavior of a single product.
*/
@Slf4j
@Getter
@Setter
@Builder
@AllArgsConstructor
public class Product {
private static final int DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE = 4;
private static final double DISCOUNT_RATE = 0.2;
@NonNull private final ProductDao productDao;
@NonNull private String name;
@NonNull private Money price;
@NonNull private LocalDate expirationDate;
/**
* Save product or update if product already exist.
*/
public void save() {
try {
Optional<Product> product = productDao.findByName(name);
if (product.isPresent()) {
productDao.update(this);
} else {
productDao.save(this);
}
} catch (SQLException ex) {
LOGGER.error(ex.getMessage());
}
}
/**
* Calculate sale price of product with discount.
*/
public Money getSalePrice() {
return price.minus(calculateDiscount());
}
private Money calculateDiscount() {
if (ChronoUnit.DAYS.between(LocalDate.now(), expirationDate)
< DAYS_UNTIL_EXPIRATION_WHEN_DISCOUNT_ACTIVE) {
return price.multipliedBy(DISCOUNT_RATE, RoundingMode.DOWN);
}
return Money.zero(USD);
}
}

View File

@ -0,0 +1,36 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import java.sql.SQLException;
import java.util.Optional;
public interface ProductDao {
Optional<Product> findByName(String name) throws SQLException;
void save(Product product) throws SQLException;
void update(Product product) throws SQLException;
}

View File

@ -0,0 +1,92 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import static org.joda.money.CurrencyUnit.USD;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import javax.sql.DataSource;
import org.joda.money.Money;
public class ProductDaoImpl implements ProductDao {
private final DataSource dataSource;
public ProductDaoImpl(final DataSource userDataSource) {
this.dataSource = userDataSource;
}
@Override
public Optional<Product> findByName(String name) throws SQLException {
var sql = "select * from PRODUCTS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
return Optional.of(
Product.builder()
.name(rs.getString("name"))
.price(Money.of(USD, rs.getBigDecimal("price")))
.expirationDate(rs.getDate("expiration_date").toLocalDate())
.productDao(this)
.build());
} else {
return Optional.empty();
}
}
}
@Override
public void save(Product product) throws SQLException {
var sql = "insert into PRODUCTS (name, price, expiration_date) values (?, ?, ?)";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, product.getName());
preparedStatement.setBigDecimal(2, product.getPrice().getAmount());
preparedStatement.setDate(3, Date.valueOf(product.getExpirationDate()));
preparedStatement.executeUpdate();
}
}
@Override
public void update(Product product) throws SQLException {
var sql = "update PRODUCTS set price = ?, expiration_date = ? where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setBigDecimal(1, product.getPrice().getAmount());
preparedStatement.setDate(2, Date.valueOf(product.getExpirationDate()));
preparedStatement.setString(3, product.getName());
preparedStatement.executeUpdate();
}
}
}

View File

@ -0,0 +1,38 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** Tests that Domain Model example runs without errors. */
final class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[] {}));
}
}

View File

@ -0,0 +1,164 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import static org.joda.money.CurrencyUnit.USD;
import static org.junit.jupiter.api.Assertions.*;
class CustomerDaoImplTest {
public static final String INSERT_CUSTOMER_SQL = "insert into CUSTOMERS values('customer', 100)";
public static final String SELECT_CUSTOMERS_SQL = "select name, money from CUSTOMERS";
public static final String INSERT_PURCHASES_SQL =
"insert into PURCHASES values('product', 'customer')";
public static final String SELECT_PURCHASES_SQL =
"select product_name, customer_name from PURCHASES";
private DataSource dataSource;
private Product product;
private Customer customer;
private CustomerDao customerDao;
@BeforeEach
void setUp() throws SQLException {
// create db schema
dataSource = TestUtils.createDataSource();
TestUtils.deleteSchema(dataSource);
TestUtils.createSchema(dataSource);
// setup objects
customerDao = new CustomerDaoImpl(dataSource);
customer = Customer.builder().name("customer").money(Money.of(CurrencyUnit.USD,100.0)).customerDao(customerDao).build();
product =
Product.builder()
.name("product")
.price(Money.of(USD, 100.0))
.expirationDate(LocalDate.parse("2021-06-27"))
.productDao(new ProductDaoImpl(dataSource))
.build();
}
@AfterEach
void tearDown() throws SQLException {
TestUtils.deleteSchema(dataSource);
}
@Test
void shouldFindCustomerByName() throws SQLException {
var customer = customerDao.findByName("customer");
assertTrue(customer.isEmpty());
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
customer = customerDao.findByName("customer");
assertTrue(customer.isPresent());
assertEquals("customer", customer.get().getName());
assertEquals(Money.of(USD, 100), customer.get().getMoney());
}
@Test
void shouldSaveCustomer() throws SQLException {
customerDao.save(customer);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) {
assertTrue(rs.next());
assertEquals(customer.getName(), rs.getString("name"));
assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money")));
}
assertThrows(SQLException.class, () -> customerDao.save(customer));
}
@Test
void shouldUpdateCustomer() throws SQLException {
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
customer.setMoney(Money.of(CurrencyUnit.USD, 99));
customerDao.update(customer);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_CUSTOMERS_SQL)) {
assertTrue(rs.next());
assertEquals(customer.getName(), rs.getString("name"));
assertEquals(customer.getMoney(), Money.of(USD, rs.getBigDecimal("money")));
assertFalse(rs.next());
}
}
@Test
void shouldAddProductToPurchases() throws SQLException {
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource);
customerDao.addProduct(product, customer);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) {
assertTrue(rs.next());
assertEquals(product.getName(), rs.getString("product_name"));
assertEquals(customer.getName(), rs.getString("customer_name"));
assertFalse(rs.next());
}
}
@Test
void shouldDeleteProductFromPurchases() throws SQLException {
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
TestUtils.executeSQL(ProductDaoImplTest.INSERT_PRODUCT_SQL, dataSource);
TestUtils.executeSQL(INSERT_PURCHASES_SQL, dataSource);
customerDao.deleteProduct(product, customer);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_PURCHASES_SQL)) {
assertFalse(rs.next());
}
}
}

View File

@ -0,0 +1,112 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
import static org.joda.money.CurrencyUnit.USD;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class CustomerTest {
private CustomerDao customerDao;
private Customer customer;
private Product product;
@BeforeEach
void setUp() {
customerDao = mock(CustomerDao.class);
customer = Customer.builder()
.name("customer")
.money(Money.of(CurrencyUnit.USD, 100.0))
.customerDao(customerDao)
.build();
product = Product.builder()
.name("product")
.price(Money.of(USD, 100.0))
.expirationDate(LocalDate.now().plusDays(10))
.productDao(mock(ProductDao.class))
.build();
}
@Test
void shouldSaveCustomer() throws SQLException {
when(customerDao.findByName("customer")).thenReturn(Optional.empty());
customer.save();
verify(customerDao, times(1)).save(customer);
when(customerDao.findByName("customer")).thenReturn(Optional.of(customer));
customer.save();
verify(customerDao, times(1)).update(customer);
}
@Test
void shouldAddProductToPurchases() {
product.setPrice(Money.of(USD, 200.0));
customer.buyProduct(product);
assertEquals(customer.getPurchases(), new ArrayList<>());
assertEquals(customer.getMoney(), Money.of(USD,100));
product.setPrice(Money.of(USD, 100.0));
customer.buyProduct(product);
assertEquals(new ArrayList<>(Arrays.asList(product)), customer.getPurchases());
assertEquals(Money.zero(USD), customer.getMoney());
}
@Test
void shouldRemoveProductFromPurchases() {
customer.setPurchases(new ArrayList<>(Arrays.asList(product)));
customer.returnProduct(product);
assertEquals(new ArrayList<>(), customer.getPurchases());
assertEquals(Money.of(USD, 200), customer.getMoney());
customer.returnProduct(product);
assertEquals(new ArrayList<>(), customer.getPurchases());
assertEquals(Money.of(USD, 200), customer.getMoney());
}
}

View File

@ -0,0 +1,127 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.joda.money.Money;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import static org.joda.money.CurrencyUnit.USD;
import static org.junit.jupiter.api.Assertions.*;
class ProductDaoImplTest {
public static final String INSERT_PRODUCT_SQL =
"insert into PRODUCTS values('product', 100, DATE '2021-06-27')";
public static final String SELECT_PRODUCTS_SQL =
"select name, price, expiration_date from PRODUCTS";
private DataSource dataSource;
private ProductDao productDao;
private Product product;
@BeforeEach
void setUp() throws SQLException {
// create schema
dataSource = TestUtils.createDataSource();
TestUtils.deleteSchema(dataSource);
TestUtils.createSchema(dataSource);
// setup objects
productDao = new ProductDaoImpl(dataSource);
product =
Product.builder()
.name("product")
.price(Money.of(USD, 100.0))
.expirationDate(LocalDate.parse("2021-06-27"))
.productDao(productDao)
.build();
}
@AfterEach
void tearDown() throws SQLException {
TestUtils.deleteSchema(dataSource);
}
@Test
void shouldFindProductByName() throws SQLException {
var product = productDao.findByName("product");
assertTrue(product.isEmpty());
TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource);
product = productDao.findByName("product");
assertTrue(product.isPresent());
assertEquals("product", product.get().getName());
assertEquals(Money.of(USD, 100), product.get().getPrice());
assertEquals(LocalDate.parse("2021-06-27"), product.get().getExpirationDate());
}
@Test
void shouldSaveProduct() throws SQLException {
productDao.save(product);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) {
assertTrue(rs.next());
assertEquals(product.getName(), rs.getString("name"));
assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price")));
assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate());
}
assertThrows(SQLException.class, () -> productDao.save(product));
}
@Test
void shouldUpdateProduct() throws SQLException {
TestUtils.executeSQL(INSERT_PRODUCT_SQL, dataSource);
product.setPrice(Money.of(USD, 99.0));
productDao.update(product);
try (var connection = dataSource.getConnection();
var statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SELECT_PRODUCTS_SQL)) {
assertTrue(rs.next());
assertEquals(product.getName(), rs.getString("name"));
assertEquals(product.getPrice(), Money.of(USD, rs.getBigDecimal("price")));
assertEquals(product.getExpirationDate(), rs.getDate("expiration_date").toLocalDate());
}
}
}

View File

@ -0,0 +1,78 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.joda.money.Money;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Optional;
import static org.joda.money.CurrencyUnit.USD;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class ProductTest {
private ProductDao productDao;
private Product product;
@BeforeEach
void setUp() {
productDao = mock(ProductDaoImpl.class);
product = Product.builder()
.name("product")
.price(Money.of(USD, 100.0))
.expirationDate(LocalDate.now().plusDays(10))
.productDao(productDao)
.build();
}
@Test
void shouldSaveProduct() throws SQLException {
when(productDao.findByName("product")).thenReturn(Optional.empty());
product.save();
verify(productDao, times(1)).save(product);
when(productDao.findByName("product")).thenReturn(Optional.of(product));
product.save();
verify(productDao, times(1)).update(product);
}
@Test
void shouldGetSalePriceOfProduct() {
assertEquals(Money.of(USD, 100), product.getSalePrice());
product.setExpirationDate(LocalDate.now().plusDays(2));
assertEquals(Money.of(USD, 80), product.getSalePrice());
}
}

View File

@ -0,0 +1,53 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.domainmodel;
import org.h2.jdbcx.JdbcDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
public class TestUtils {
public static void executeSQL( String sql, DataSource dataSource) throws SQLException {
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
public static void createSchema(DataSource dataSource) throws SQLException {
TestUtils.executeSQL(App.CREATE_SCHEMA_SQL, dataSource);
}
public static void deleteSchema(DataSource dataSource) throws SQLException {
TestUtils.executeSQL(App.DELETE_SCHEMA_SQL, dataSource);
}
public static DataSource createDataSource() {
var dataSource = new JdbcDataSource();
dataSource.setURL(App.H2_DB_URL);
return dataSource;
}
}

View File

@ -24,7 +24,6 @@ Use an Event-driven architecture when
## Real world examples
* SendGrid, an email API, sends events whenever an email is processed, delivered, opened etc... (https://sendgrid.com/docs/API_Reference/Webhooks/event.html)
* Chargify, a billing API, exposes payment activity through various events (https://docs.chargify.com/api-events)
* Amazon's AWS Lambda, lets you execute code in response to events such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices. (https://aws.amazon.com/lambda)
* MySQL runs triggers based on events such as inserts and update events happening on database tables.
@ -32,6 +31,6 @@ Use an Event-driven architecture when
## Credits
* [Event-driven architecture - Wikipedia](https://en.wikipedia.org/wiki/Event-driven_architecture)
* [Fundamental Components of an Event-Driven Architecture](http://giocc.com/fundamental-components-of-an-event-driven-architecture.html)
* [What is an Event-Driven Architecture](https://aws.amazon.com/event-driven-architecture/)
* [Real World Applications/Event Driven Applications](https://wiki.haskell.org/Real_World_Applications/Event_Driven_Applications)
* [Event-driven architecture definition](http://searchsoa.techtarget.com/definition/event-driven-architecture)

View File

@ -17,7 +17,7 @@ interface that makes the subsystem easier to use.
## Explanation
Real world example
Real-world example
> How does a goldmine work? "Well, the miners go down there and dig gold!" you say. That is what you
> believe because you are using a simple interface that goldmine provides on the outside, internally

View File

@ -7,7 +7,7 @@ categories: Creational
language: en
tags:
- Extensibility
- Gang Of Four
- Gang of Four
---
## Also known as
@ -21,7 +21,7 @@ Factory Method lets a class defer instantiation to subclasses.
## Explanation
Real world example
Real-world example
> Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons.
> Depending on the customer at hand the right type of blacksmith is summoned.
@ -40,7 +40,7 @@ Wikipedia says
**Programmatic Example**
Taking our blacksmith example above. First of all we have a `Blacksmith` interface and some
Taking our blacksmith example above. First of all, we have a `Blacksmith` interface and some
implementations for it:
```java
@ -65,15 +65,25 @@ When the customers come, the correct type of blacksmith is summoned and requeste
manufactured:
```java
var blacksmith = new ElfBlacksmith();
blacksmith.manufactureWeapon(WeaponType.SPEAR);
blacksmith.manufactureWeapon(WeaponType.AXE);
Blacksmith blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
```
Program output:
```java
// Elven spear
// Elven axe
```
The orc blacksmith manufactured an orcish spear
The orc blacksmith manufactured an orcish axe
The elf blacksmith manufactured an elven spear
The elf blacksmith manufactured an elven axe
```
## Class diagram
@ -89,7 +99,7 @@ Use the Factory Method pattern when:
* Classes delegate responsibility to one of several helper subclasses, and you want to localize the
knowledge of which helper subclass is the delegate.
## Real world examples
## Known uses
* [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--)
* [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-)

View File

@ -26,7 +26,7 @@ package com.iluwatar.factory.method;
import lombok.extern.slf4j.Slf4j;
/**
* The Factory Method is a creational design pattern which uses factory methods to deal with the
* The Factory Method is a creational design pattern that uses factory methods to deal with the
* problem of creating objects without specifying the exact class of object that will be created.
* This is done by creating objects via calling a factory method either specified in an interface
* and implemented by child classes, or implemented in a base class and optionally overridden by
@ -41,39 +41,22 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class App {
private final Blacksmith blacksmith;
/**
* Creates an instance of <code>App</code> which will use <code>blacksmith</code> to manufacture
* the weapons for war.
* <code>App</code> is unaware which concrete implementation of {@link Blacksmith} it is using.
* The decision of which blacksmith implementation to use may depend on configuration, or
* the type of rival in war.
* @param blacksmith a non-null implementation of blacksmith
*/
public App(Blacksmith blacksmith) {
this.blacksmith = blacksmith;
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// Lets go to war with Orc weapons
var app = new App(new OrcBlacksmith());
app.manufactureWeapons();
// Lets go to war with Elf weapons
app = new App(new ElfBlacksmith());
app.manufactureWeapons();
}
private void manufactureWeapons() {
var weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info(weapon.toString());
Blacksmith blacksmith = new OrcBlacksmith();
Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info(weapon.toString());
LOGGER.info("{} manufactured {}", blacksmith, weapon);
blacksmith = new ElfBlacksmith();
weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
LOGGER.info("{} manufactured {}", blacksmith, weapon);
}
}

View File

@ -44,4 +44,8 @@ public class ElfBlacksmith implements Blacksmith {
return ELFARSENAL.get(weaponType);
}
@Override
public String toString() {
return "The elf blacksmith";
}
}

View File

@ -37,6 +37,6 @@ public class ElfWeapon implements Weapon {
@Override
public String toString() {
return "Elven " + weaponType;
return "an elven " + weaponType;
}
}

View File

@ -43,4 +43,9 @@ public class OrcBlacksmith implements Blacksmith {
public Weapon manufactureWeapon(WeaponType weaponType) {
return ORCARSENAL.get(weaponType);
}
@Override
public String toString() {
return "The orc blacksmith";
}
}

View File

@ -37,6 +37,6 @@ public class OrcWeapon implements Weapon {
@Override
public String toString() {
return "Orcish " + weaponType;
return "an orcish " + weaponType;
}
}

View File

@ -16,16 +16,17 @@ tags:
## Intent
Providing a static method encapsulated in a class called factory, in order to hide the
implementation logic and makes client code focus on usage rather then initialization new objects.
Providing a static method encapsulated in a class called the factory, to hide the implementation
logic and make client code focus on usage rather than initializing new objects.
## Explanation
Real world example
Real-world example
> Lets say we have a web application connected to SQLServer, but now we want to switch to Oracle. To
> do so without modifying existing source code, we need to implements Simple Factory pattern, in
> which a static method can be invoked to create connection to a given database.
> Imagine an alchemist who is about to manufacture coins. The alchemist must be able to create both
> gold and copper coins and switching between them must be possible without modifying the existing
> source code. The factory pattern makes it possible by providing a static construction method which
> can be called with relevant parameters.
Wikipedia says
@ -34,16 +35,16 @@ Wikipedia says
**Programmatic Example**
We have an interface `Car` and two implementations `Ford` and `Ferrari`.
We have an interface `Coin` and two implementations `GoldCoin` and `CopperCoin`.
```java
public interface Car {
public interface Coin {
String getDescription();
}
public class Ford implements Car {
public class GoldCoin implements Coin {
static final String DESCRIPTION = "This is Ford.";
static final String DESCRIPTION = "This is a gold coin.";
@Override
public String getDescription() {
@ -51,9 +52,9 @@ public class Ford implements Car {
}
}
public class Ferrari implements Car {
public class CopperCoin implements Coin {
static final String DESCRIPTION = "This is Ferrari.";
static final String DESCRIPTION = "This is a copper coin.";
@Override
public String getDescription() {
@ -62,51 +63,48 @@ public class Ferrari implements Car {
}
```
Enumeration above represents types of cars that we support (`Ford` and `Ferrari`).
Enumeration above represents types of coins that we support (`GoldCoin` and `CopperCoin`).
```java
public enum CarType {
FORD(Ford::new),
FERRARI(Ferrari::new);
private final Supplier<Car> constructor;
CarType(Supplier<Car> constructor) {
this.constructor = constructor;
}
public Supplier<Car> getConstructor() {
return this.constructor;
}
@RequiredArgsConstructor
@Getter
public enum CoinType {
COPPER(CopperCoin::new),
GOLD(GoldCoin::new);
private final Supplier<Coin> constructor;
}
```
Then we have the static method `getCar` to create car objects encapsulated in the factory class
`CarsFactory`.
Then we have the static method `getCoin` to create coin objects encapsulated in the factory class
`CoinFactory`.
```java
public class CarsFactory {
public static Car getCar(CarType type) {
public class CoinFactory {
public static Coin getCoin(CoinType type) {
return type.getConstructor().get();
}
}
```
Now on the client code we can create different types of cars using the factory class.
Now on the client code we can create different types of coins using the factory class.
```java
var car1 = CarsFactory.getCar(CarType.FORD);
var car2 = CarsFactory.getCar(CarType.FERRARI);
LOGGER.info(car1.getDescription());
LOGGER.info(car2.getDescription());
LOGGER.info("The alchemist begins his work.");
var coin1 = CoinFactory.getCoin(CoinType.COPPER);
var coin2 = CoinFactory.getCoin(CoinType.GOLD);
LOGGER.info(coin1.getDescription());
LOGGER.info(coin2.getDescription());
```
Program output:
```java
This is Ford.
This is Ferrari.
The alchemist begins his work.
This is a copper coin.
This is a gold coin.
```
## Class Diagram
@ -115,7 +113,7 @@ This is Ferrari.
## Applicability
Use the Simple Factory pattern when you only care about the creation of a object, not how to create
Use the factory pattern when you only care about the creation of a object, not how to create
and manage it.
Pros
@ -127,13 +125,13 @@ Cons
* The code becomes more complicated than it should be.
## Real world examples
## Known uses
* [java.util.Calendar#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--)
* [java.util.ResourceBundle#getBundle()](https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-)
* [java.text.NumberFormat#getInstance()](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--)
* [java.nio.charset.Charset#forName()](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-)
* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (Returns different singleton objects, depending on a protocol)
* [java.net.URLStreamHandlerFactory#createURLStreamHandler(String)](https://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html) (returns different singleton objects, depending on a protocol)
* [java.util.EnumSet#of()](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of(E))
* [javax.xml.bind.JAXBContext#createMarshaller()](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) and other similar methods.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

@ -5,31 +5,32 @@ package com.iluwatar.factory {
+ App()
+ main(args : String[]) {static}
}
interface Car {
interface Coin {
+ getDescription() : String {abstract}
}
class CarsFactory {
+ CarsFactory()
+ getCar(type : CarType) : Car {static}
class CoinFactory {
+ CoinFactory()
+ getCoin(type : CoinType) : Coin {static}
}
~enum CarType {
+ FERRARI {static}
+ FORD {static}
+ valueOf(name : String) : CarType {static}
+ values() : CarType[] {static}
enum CoinType {
+ COPPER {static}
+ GOLD {static}
- constructor : Supplier<Coin>
+ getConstructor() : Supplier<Coin>
+ valueOf(name : String) : CoinType {static}
+ values() : CoinType[] {static}
}
class Ferrari {
class CopperCoin {
~ DESCRIPTION : String {static}
+ Ferrari()
+ CopperCoin()
+ getDescription() : String
}
class Ford {
class GoldCoin {
~ DESCRIPTION : String {static}
+ Ford()
+ GoldCoin()
+ getDescription() : String
}
}
CarType ..+ CarsFactory
Ferrari ..|> Car
Ford ..|> Car
CopperCoin ..|> Coin
GoldCoin ..|> Coin
@enduml

View File

@ -30,8 +30,8 @@ import lombok.extern.slf4j.Slf4j;
* create and return objects of varying classes, in order to hide the implementation logic
* and makes client code focus on usage rather then objects initialization and management.
*
* <p>In this example the CarFactory is the factory class and it provides a static method to
* create different cars.
* <p>In this example an alchemist manufactures coins. CoinFactory is the factory class and it
* provides a static method to create different types of coins.
*/
@Slf4j
@ -41,9 +41,10 @@ public class App {
* Program main entry point.
*/
public static void main(String[] args) {
var car1 = CarsFactory.getCar(CarType.FORD);
var car2 = CarsFactory.getCar(CarType.FERRARI);
LOGGER.info(car1.getDescription());
LOGGER.info(car2.getDescription());
LOGGER.info("The alchemist begins his work.");
var coin1 = CoinFactory.getCoin(CoinType.COPPER);
var coin2 = CoinFactory.getCoin(CoinType.GOLD);
LOGGER.info(coin1.getDescription());
LOGGER.info(coin2.getDescription());
}
}

View File

@ -24,9 +24,9 @@
package com.iluwatar.factory;
/**
* Car interface.
* Coin interface.
*/
public interface Car {
public interface Coin {
String getDescription();

View File

@ -24,14 +24,14 @@
package com.iluwatar.factory;
/**
* Factory of cars.
* Factory of coins.
*/
public class CarsFactory {
public class CoinFactory {
/**
* Factory method takes as parameter a car type and initiate the appropriate class.
* Factory method takes as a parameter the coin type and calls the appropriate class.
*/
public static Car getCar(CarType type) {
public static Coin getCoin(CoinType type) {
return type.getConstructor().get();
}
}

View File

@ -28,15 +28,14 @@ import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Enumeration for different types of cars.
* Enumeration for different types of coins.
*/
@RequiredArgsConstructor
@Getter
public enum CarType {
public enum CoinType {
FORD(Ford::new),
FERRARI(Ferrari::new);
private final Supplier<Car> constructor;
COPPER(CopperCoin::new),
GOLD(GoldCoin::new);
private final Supplier<Coin> constructor;
}

View File

@ -24,11 +24,11 @@
package com.iluwatar.factory;
/**
* Ford implementation.
* CopperCoin implementation.
*/
public class Ford implements Car {
public class CopperCoin implements Coin {
static final String DESCRIPTION = "This is Ford.";
static final String DESCRIPTION = "This is a copper coin.";
@Override
public String getDescription() {

View File

@ -24,11 +24,11 @@
package com.iluwatar.factory;
/**
* Ferrari implementation.
* GoldCoin implementation.
*/
public class Ferrari implements Car {
public class GoldCoin implements Coin {
static final String DESCRIPTION = "This is Ferrari.";
static final String DESCRIPTION = "This is a gold coin.";
@Override
public String getDescription() {

View File

@ -27,12 +27,11 @@ import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class CarsFactoryTest {
class CoinFactoryTest {
@Test
void shouldReturnFerrariInstance() {
final var ferrari = CarsFactory.getCar(CarType.FERRARI);
assertTrue(ferrari instanceof Ferrari);
void shouldReturnGoldCoinInstance() {
final var goldCoin = CoinFactory.getCoin(CoinType.GOLD);
assertTrue(goldCoin instanceof GoldCoin);
}
}

120
fanout-fanin/README.md Normal file
View File

@ -0,0 +1,120 @@
---
layout: pattern
title: Fan-Out/Fan-In
folder: fanout-fanin
permalink: /patterns/fanout-fanin/
categories: Integration
language: en
tags:
- Microservices
---
## Intent
The pattern is used when a source system needs to run one or more long-running processes that will fetch some data.
The source will not block itself waiting for the reply. <br> The pattern will run the same function in multiple
services or machines to fetch the data. This is equivalent to invoking the function multiple times on different chunks of data.
## Explanation
The FanOut/FanIn service will take in a list of requests and a consumer. Each request might complete at a different time.
FanOut/FanIn service will accept the input params and returns the initial system an ID to acknowledge that the pattern
service has received the requests. Now the caller will not wait or expect the result in the same connection.
Meanwhile, the pattern service will invoke the requests that have come. The requests might complete at different time.
These requests will be processed in different instances of the same function in different machines or services. As the
requests get completed, a callback service everytime is called that transforms the result into a common single object format
that gets pushed to a consumer. The caller will be at the other end of the consumer receiving the result.
**Programmatic Example**
The implementation provided has a list of numbers and end goal is to square the numbers and add them to a single result.
`FanOutFanIn` class receives the list of numbers in the form of list of `SquareNumberRequest` and a `Consumer` instance
that collects the results as the requests get over. `SquareNumberRequest` will square the number with a random delay
to give the impression of a long-running process that can complete at any time. `Consumer` instance will add the results from
different `SquareNumberRequest` that will come random time instances.
Let's look at `FanOutFanIn` class that fans out the requests in async processes.
```java
public class FanOutFanIn {
public static Long fanOutFanIn(
final List<SquareNumberRequest> requests, final Consumer consumer) {
ExecutorService service = Executors.newFixedThreadPool(requests.size());
// fanning out
List<CompletableFuture<Void>> futures =
requests.stream()
.map(
request ->
CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
return consumer.getSumOfSquaredNumbers().get();
}
}
```
`Consumer` is used a callback class that will be called when a request is completed. This will aggregate
the result from all requests.
```java
public class Consumer {
private final AtomicLong sumOfSquaredNumbers;
Consumer(Long init) {
sumOfSquaredNumbers = new AtomicLong(init);
}
public Long add(final Long num) {
return sumOfSquaredNumbers.addAndGet(num);
}
}
```
Request is represented as a `SquareNumberRequest` that squares the number with random delay and calls the
`Consumer` once it is squared.
```java
public class SquareNumberRequest {
private final Long number;
public void delayedSquaring(final Consumer consumer) {
var minTimeOut = 5000L;
SecureRandom secureRandom = new SecureRandom();
var randomTimeOut = secureRandom.nextInt(2000);
try {
// this will make the thread sleep from 5-7s.
Thread.sleep(minTimeOut + randomTimeOut);
} catch (InterruptedException e) {
LOGGER.error("Exception while sleep ", e);
Thread.currentThread().interrupt();
} finally {
consumer.add(number * number);
}
}
}
```
## Class diagram
![alt-text](./etc/fanout-fanin.png)
## Applicability
Use this pattern when you can divide the workload into multiple chunks that can be dealt with separately.
## Related patterns
* [Aggregator Microservices](https://java-design-patterns.com/patterns/aggregator-microservices/)
* [API Gateway](https://java-design-patterns.com/patterns/api-gateway/)
## Credits
* [Understanding Azure Durable Functions - Part 8: The Fan Out/Fan In Pattern](http://dontcodetired.com/blog/post/Understanding-Azure-Durable-Functions-Part-8-The-Fan-OutFan-In-Pattern)
* [Fan-out/fan-in scenario in Durable Functions - Cloud backup example](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-cloud-backup)
* [Understanding the Fan-Out/Fan-In API Integration Pattern](https://dzone.com/articles/understanding-the-fan-out-fan-in-api-integration-p)

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@ -0,0 +1,39 @@
@startuml
package com.iluwatar.fanout.fanin {
class App {
- LOGGER : Logger {static}
+ App()
+ main(args : String[]) {static}
}
class Consumer {
- sumOfSquaredNumbers : AtomicLong
~ Consumer(init : Long)
+ add(num : Long) : Long
+ getSumOfSquaredNumbers() : AtomicLong
}
class FanOutFanIn {
+ FanOutFanIn()
+ fanOutFanIn(requests : List<SquareNumberRequest>, consumer : Consumer) : Long {static}
}
class SquareNumberRequest {
- LOGGER : Logger {static}
- number : Long
+ SquareNumberRequest(number : Long)
+ delayedSquaring(consumer : Consumer)
}
object SquareNumberRequest1
object SquareNumberRequest2
object SquareNumberRequest3
diamond dia
}
App --> FanOutFanIn
FanOutFanIn --> "fan out - running in parallel" SquareNumberRequest1
FanOutFanIn --> "fan out" SquareNumberRequest2
FanOutFanIn --> "fan out" SquareNumberRequest3
SquareNumberRequest1 --> "fan in - aggregate using callback" dia
SquareNumberRequest2 --> "fan in" dia
SquareNumberRequest3 --> "fan in" dia
dia --> Consumer
@enduml

69
fanout-fanin/pom.xml Normal file
View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License (MIT)
Copyright © 2014-2021 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.
Module Model-view-viewmodel is using ZK framework
ZK framework is licensed under LGPL and the license can be found at lgpl-3.0.txt
-->
<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">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.25.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>fanout-fanin</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.fanout.fanin.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,74 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* FanOut/FanIn pattern is a concurrency pattern that refers to executing multiple instances of the
* activity function concurrently. The "fan out" part is essentially splitting the data into
* multiple chunks and then calling the activity function multiple times, passing the chunks.
*
* <p>When each chunk has been processed, the "fan in" takes place that aggregates results from each
* instance of function and forms a single final result.
*
* <p>This pattern is only really useful if you can “chunk” the workload in a meaningful way for
* splitting up to be processed in parallel.
*/
@Slf4j
public class App {
/**
* Entry point.
*
* <p>Implementation provided has a list of numbers that has to be squared and added. The list can
* be chunked in any way and the "activity function" {@link
* SquareNumberRequest#delayedSquaring(Consumer)} i.e. squaring the number ca be done
* concurrently. The "fan in" part is handled by the {@link Consumer} that takes in the result
* from each instance of activity and aggregates it whenever that particular activity function
* gets over.
*/
public static void main(String[] args) {
final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L);
LOGGER.info("Numbers to be squared and get sum --> {}", numbers);
final List<SquareNumberRequest> requests =
numbers.stream().map(SquareNumberRequest::new).collect(Collectors.toList());
var consumer = new Consumer(0L);
// Pass the request and the consumer to fanOutFanIn or sometimes referred as Orchestrator
// function
final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer);
LOGGER.info("Sum of all squared numbers --> {}", sumOfSquaredNumbers);
}
}

View File

@ -0,0 +1,48 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import java.util.concurrent.atomic.AtomicLong;
import lombok.Getter;
/**
* Consumer or callback class that will be called everytime a request is complete This will
* aggregate individual result to form a final result.
*/
@Getter
public class Consumer {
private final AtomicLong sumOfSquaredNumbers;
Consumer(Long init) {
sumOfSquaredNumbers = new AtomicLong(init);
}
public Long add(final Long num) {
return sumOfSquaredNumbers.addAndGet(num);
}
}

View File

@ -0,0 +1,62 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
/**
* FanOutFanIn class processes long running requests, when any of the processes gets over, result is
* passed over to the consumer or the callback function. Consumer will aggregate the results as they
* keep on completing.
*/
public class FanOutFanIn {
/**
* the main fanOutFanIn function or orchestrator function.
* @param requests List of numbers that need to be squared and summed up
* @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up
* @return Aggregated sum of all squared numbers.
*/
public static Long fanOutFanIn(
final List<SquareNumberRequest> requests, final Consumer consumer) {
ExecutorService service = Executors.newFixedThreadPool(requests.size());
// fanning out
List<CompletableFuture<Void>> futures =
requests.stream()
.map(
request ->
CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
return consumer.getSumOfSquaredNumbers().get();
}
}

View File

@ -0,0 +1,63 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import java.security.SecureRandom;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Squares the number with a little timeout to give impression of long running process that return
* at different times.
*/
@Slf4j
@AllArgsConstructor
public class SquareNumberRequest {
private final Long number;
/**
* Squares the number with a little timeout to give impression of long running process that return
* at different times.
* @param consumer callback class that takes the result after the delay.
* */
public void delayedSquaring(final Consumer consumer) {
var minTimeOut = 5000L;
SecureRandom secureRandom = new SecureRandom();
var randomTimeOut = secureRandom.nextInt(2000);
try {
// this will make the thread sleep from 5-7s.
Thread.sleep(minTimeOut + randomTimeOut);
} catch (InterruptedException e) {
LOGGER.error("Exception while sleep ", e);
Thread.currentThread().interrupt();
} finally {
consumer.add(number * number);
}
}
}

View File

@ -0,0 +1,36 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
class AppTest {
@Test
void shouldLaunchApp() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -0,0 +1,47 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class FanOutFanInTest {
@Test
void fanOutFanInTest() {
final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L);
final List<SquareNumberRequest> requests =
numbers.stream().map(SquareNumberRequest::new).collect(Collectors.toList());
final Consumer consumer = new Consumer(0L);
final Long sumOfSquaredNumbers = FanOutFanIn.fanOutFanIn(requests, consumer);
Assertions.assertEquals(139, sumOfSquaredNumbers);
}
}

View File

@ -0,0 +1,41 @@
/*
* The MIT License
* Copyright © 2014-2021 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 com.iluwatar.fanout.fanin;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SquareNumberRequestTest {
@Test
void delayedSquaringTest() {
Consumer consumer = new Consumer(10L);
SquareNumberRequest squareNumberRequest = new SquareNumberRequest(5L);
squareNumberRequest.delayedSquaring(consumer);
Assertions.assertEquals(35, consumer.getSumOfSquaredNumbers().get());
}
}

View File

@ -3,10 +3,8 @@ layout: pattern
title: Filterer
folder: filterer
permalink: /patterns/filterer/
description: Design pattern that helps container-like objects to return filtered version of themselves.# short meta description that shows in Google search results
language: en
categories:
- Functional
categories: Functional
tags:
- Extensibility
---

View File

@ -23,11 +23,14 @@
package com.iluwatar.filterer;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
class AppTest {
@Test
void shouldLaunchApp() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -6,7 +6,7 @@ permalink: /patterns/flyweight/
categories: Structural
language: en
tags:
- Gang Of Four
- Gang of Four
- Performance
---
@ -16,11 +16,11 @@ Use sharing to support large numbers of fine-grained objects efficiently.
## Explanation
Real world example
Real-world example
> Alchemist's shop has shelves full of magic potions. Many of the potions are the same so there is
> no need to create new object for each of them. Instead one object instance can represent multiple
> shelf items so memory footprint remains small.
> no need to create a new object for each of them. Instead, one object instance can represent
> multiple shelf items so the memory footprint remains small.
In plain words
@ -36,7 +36,7 @@ Wikipedia says
**Programmatic example**
Translating our alchemist shop example from above. First of all we have different potion types:
Translating our alchemist shop example from above. First of all, we have different potion types:
```java
public interface Potion {
@ -104,27 +104,81 @@ public class PotionFactory {
}
```
And it can be used as below:
`AlchemistShop` contains two shelves of magic potions. The potions are created using the
aforementioned `PotionFactory`.
```java
var factory = new PotionFactory();
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)
factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364)
factory.createPotion(PotionType.INVISIBILITY).drink(); // You become invisible. (Potion=6566818)
factory.createPotion(PotionType.HOLY_WATER).drink(); // You feel blessed. (Potion=1104106489)
factory.createPotion(PotionType.HOLY_WATER).drink(); // You feel blessed. (Potion=1104106489)
factory.createPotion(PotionType.HEALING).drink(); // You feel healed. (Potion=648129364)
@Slf4j
public class AlchemistShop {
private final List<Potion> topShelf;
private final List<Potion> bottomShelf;
public AlchemistShop() {
var factory = new PotionFactory();
topShelf = List.of(
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.STRENGTH),
factory.createPotion(PotionType.HEALING),
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.STRENGTH),
factory.createPotion(PotionType.HEALING),
factory.createPotion(PotionType.HEALING)
);
bottomShelf = List.of(
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.HOLY_WATER),
factory.createPotion(PotionType.HOLY_WATER)
);
}
public final List<Potion> getTopShelf() {
return List.copyOf(this.topShelf);
}
public final List<Potion> getBottomShelf() {
return List.copyOf(this.bottomShelf);
}
public void drinkPotions() {
LOGGER.info("Drinking top shelf potions\n");
topShelf.forEach(Potion::drink);
LOGGER.info("Drinking bottom shelf potions\n");
bottomShelf.forEach(Potion::drink);
}
}
```
In our scenario, a brave visitor enters the alchemist shop and drinks all the potions.
```java
// create the alchemist shop with the potions
var alchemistShop = new AlchemistShop();
// a brave visitor enters the alchemist shop and drinks all the potions
alchemistShop.drinkPotions();
```
Program output:
```java
You become invisible. (Potion=6566818)
You feel healed. (Potion=648129364)
You become invisible. (Potion=6566818)
You feel blessed. (Potion=1104106489)
You feel blessed. (Potion=1104106489)
You feel healed. (Potion=648129364)
Drinking top shelf potions
You become invisible. (Potion=1509514333)
You become invisible. (Potion=1509514333)
You feel strong. (Potion=739498517)
You feel healed. (Potion=125130493)
You become invisible. (Potion=1509514333)
You feel strong. (Potion=739498517)
You feel healed. (Potion=125130493)
You feel healed. (Potion=125130493)
Drinking bottom shelf potions
Urgh! This is poisonous. (Potion=166239592)
Urgh! This is poisonous. (Potion=166239592)
Urgh! This is poisonous. (Potion=166239592)
You feel blessed. (Potion=991505714)
You feel blessed. (Potion=991505714)
```
## Class diagram
@ -138,13 +192,13 @@ Flyweight pattern when all of the following are true:
* An application uses a large number of objects.
* Storage costs are high because of the sheer quantity of objects.
* Most object state can be made extrinsic.
* Many groups of objects may be replaced by relatively few shared objects once extrinsic state is
removed.
* Most of the object state can be made extrinsic.
* Many groups of objects may be replaced by relatively few shared objects once the extrinsic state
is removed.
* The application doesn't depend on object identity. Since flyweight objects may be shared, identity
tests will return true for conceptually distinct objects.
## Real world examples
## Known uses
* [java.lang.Integer#valueOf(int)](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf%28int%29) and similarly for Byte, Character and other wrapped types.

View File

@ -78,12 +78,12 @@ public class AlchemistShop {
}
/**
* Enumerate potions.
* Drink all the potions.
*/
public void enumerate() {
LOGGER.info("Enumerating top shelf potions\n");
public void drinkPotions() {
LOGGER.info("Drinking top shelf potions");
topShelf.forEach(Potion::drink);
LOGGER.info("Enumerating bottom shelf potions\n");
LOGGER.info("Drinking bottom shelf potions");
bottomShelf.forEach(Potion::drink);
}
}

View File

@ -43,7 +43,9 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
// create the alchemist shop with the potions
var alchemistShop = new AlchemistShop();
alchemistShop.enumerate();
// a brave visitor enters the alchemist shop and drinks all the potions
alchemistShop.drinkPotions();
}
}

Some files were not shown because too many files have changed in this diff Show More