* #1771 Move translations to a new directory to have more organization
* #1771 spanish translation
* #1771 change the language codes to follow ISO 639-1 and change the links
* #1771 remove country flags
* Fix languages
* Missed change for version number
* Add language field for presentation
* Revert change in README for double buffer
Co-authored-by: Jackie Nim <=>
* Correcting the Hyperlink to redirect to the correct URL.
Corresponds to bug #1703
* Deleting the extra Hyphen(-) that was incorrectly added.
* Corrected the contributors inside the Readme file.
Updated the correct number of contributors to be in sync with `master`
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* docs: translated docs to zh
* docs: translated doc of sharding pattern to Chinese
* docs: translated doc of factory pattern to Chinese
* docs: translated doc of factory-kit pattern to Chinese
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* Correct README.md in Korean
Spelling correction and human-readable paraphrase on ko/README.md. Previously, it was translated using a machine translator.
* Add strategy pattern into Korean
Add and translate the strategy pattern into Korean.
* Remove source file from the translated folder
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* Updated saga to JUnit 5
* Update fix for CI job in trampoline module
* Updated update-method module to JUnit 5
* Upgraded to latest JUnit Jupiter
JUnit 4 is not needed when using JUnit-Vintage
* Reverted change to access modifier on Trampoline
* Cleanup to resolve code smells
* Formatting
* Formatting
* Migrating to JUnit5 and updating some Mockito patterns
* Migrating to JUnit5
* Migrating to JUnit5
* Migrating to JUnit 5
* Formatting cleanup
* Added missing scope for junit
* Fixed tests that were not running previously.
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* Updated saga to JUnit 5
* Update fix for CI job in trampoline module
* Updated update-method module to JUnit 5
* Upgraded to latest JUnit Jupiter
JUnit 4 is not needed when using JUnit-Vintage
* Reverted change to access modifier on Trampoline
* Cleanup to resolve code smells
* Formatting
* Formatting
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* #455 work on readme.md
* #455 work on readme.md
* #455 S3 web site complete
* #455 add cloudfront and diagram
* Apply suggestions from code review
added syntax highlighting
Co-authored-by: Subhrodip Mohanta <hello@subho.xyz>
* #1625 init Turkish translation and add the flag
* #1625 update the Main README.md for Turkish translation
* #1625 add Turkish translation for README.md
Co-authored-by: Halil Demir <halil.demir@zalando.de>
* #1317 Add Special Case Pattern
To focus on pattern itself, I implement DB and
maintenance lock by the singleton instance.
* #1317 Add special cases unit tests
Assert the logger output
(ref: https://stackoverflow.com/a/52229629)
* #1317 Add README.md
Add Special Case Pattern README
* #1317 Format: add a new line to end of file
Co-authored-by: Subhrodip Mohanta <subhrodipmohanta@gmail.com>
* 🚀 init fr translation
* #1620 evo add french translation - main part
* #1620 evo add french translation - main part
* #1620 evo french translation - add french flag
* Update README.md
* Update README.md
* #1620 add cn and kr flags
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* #1569 DTO pattern implemented using Enums
* #1569 DTO pattern implemented using Enums
* #1569 adding some java docs
* #1569 some changes in java doc and code style
* #1569 some changes in java doc and code style
* #1569 some changes in java doc and code style
* #1569 some changes in java doc and code style
* #1569 adding suggested extra line
* #1569 license added to pom.xml
* #1569 more checkstyle problems resolved
* #1569 more checkstyle problems resolved
* #1569 more checkstyle problems resolved
Co-authored-by: siavashsoleymani <siavash.soleimani@snapp.cab>
Co-authored-by: Subhrodip Mohanta <subhrodipmohanta@gmail.com>
* Getting @Test from JUnit5 instead of JUnit4
* Changed FixedStepGameLoopTest.java imports and tests to JUnit5
* JUnit4 to JUnit5
* JUnit4 to JUnit5
* JUnit4 to JUnit5
* JUnit4 to JUnit5
* add state and callback pattern
* add command and template-method pattern
* add iterator pattern
* add bridege and DI pattern
* fix issue #1600
Co-authored-by: Mike <admin@xiaod.info>
Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>
This fixes a security vulnerability in this project where the `pom.xml`
files were configuring Maven to resolve dependencies over HTTP instead of
HTTPS.
Signed-off-by: Jonathan Leitschuh <Jonathan.Leitschuh@gmail.com>
* Adding support for maven assembly plugin to generate executable jar with all dependencies in built
* Merge branch 'master' into issue-989
# Conflicts:
# abstract-document/pom.xml
# pom.xml
* Adding maven assemly plugin for projects with name A
* Update in format as per checkstyle, i.e. Spcae in place of tab with size of 2
* batch set - 2 having all project with B and C
* issue-989 d-e-f
* fixing eip pom and adding g-h-i-l-m-n Skipping naked object as it seems it doesn't have main method, will consider this at end
* Adding for O and P projects Skipping Object-Mother as we don't have main method for same.
* Final batch
* Adding support for maven assembly plugin to generate executable jar with all dependencies in built
* Merge branch 'master' into issue-989
# Conflicts:
# abstract-document/pom.xml
# pom.xml
* Adding maven assemly plugin for projects with name A
* Update in format as per checkstyle, i.e. Spcae in place of tab with size of 2
* batch set - 2 having all project with B and C
* issue-989 d-e-f
* fixing eip pom and adding g-h-i-l-m-n Skipping naked object as it seems it doesn't have main method, will consider this at end
* Adding for O and P projects Skipping Object-Mother as we don't have main method for same.
* Declares the template methods as final
* Extends the description of the template method pattern
* Removes the final declarations (this was done in another branch)
* Adding support for maven assembly plugin to generate executable jar with all dependencies in built
* Merge branch 'master' into issue-989
# Conflicts:
# abstract-document/pom.xml
# pom.xml
* Adding maven assemly plugin for projects with name A
* Update in format as per checkstyle, i.e. Spcae in place of tab with size of 2
* Resolution proposition to Issue#1055 (UML diagram left to do)
* Deciding not to modify the UML diagram for now
* Resolution proposition to Issue#1093
* Code reformatting
* init repo for role object
* add to init
* add to init
* add first impl
* add pattern
* add license
* add changes
* add saga init dsc
* add init saga dsc
* add changes to dsc
* add
* add orchestrator
* add ch
* separate pkgs
* add info
* add choreogr
* rem space
* change according to cgeckstyle
* add changes according to google style
* Reduces checkstyle errors in facade
* Reduces checkstyle errors in factory-kit
* Reduces checkstyle errors in spatial-partition
* Reduces checkstyle errors in state
* Reduces checkstyle errors in step-builder
* Fix for Issue##549
Catch ClientProtocolException and Update Error Logs
* Fix indentation, checkstyle errors
* Fix for Issue #549
Add fallbacks in Aggregator service when other microservices fail
* Make ProductInventoryClientImpl return null instead of zero in case of failure
* Using static object to reduce memory foot prints
* Updating README along with name of static fields
* Updating code as per review comments
* Updating code as per review comments
* Updating doc as per new code
* local variable type inference changes
local variable type inference changes for thread pool design pattern
* local variable type inference changes
local variable type inference changes for ThreadPool design pattern
* local variable type inference changes
replacing type with var
* the type changed back to String
since it is initializing to null and later having different value, it is throwing error in Travis-CI. Made changes.
* Add custom license header style in order to comply with Google's Checkstyle format
* Update license headers to comply with Google's Checkstyle format
* "visitor" pattern: Use local variable type inference
Update "visitor" pattern with local variable type inference.
* "value-object" pattern: Use local variable type inference
Update "value-object" pattern with local variable type inference.
* "unit-of-work" pattern: Use local variable type inference
Update "value-object" pattern with local variable type inference.
* "typeobjectpattern" pattern: Use local variable type inference
Update "value-object" pattern with local variable type inference.
* Basic implementation
* implement double buffer
* add unit test
* add unit test
* Add Readme
* Change local value declaration to var
* Remove unused fields
The two remaining files were still creating a Random everytime the method
was called. These were missed in the previous commit because the previous
commit had fixed only one of the methods; in other words, there were
multiple methods that were creating the Random object on each call.
* 1011: Added SuppressWarnings for SonarCloud errors
All of these files are causing SonarCloud to report the following error:
Loops should not be infinite
Since these instances all require an infinite loop that will never end,
these warnings should be disabled so that SonarCloud no longer reports
them as error.
The rule is: squid:S2189
* 1011: Made all of the randoms static and final
According to SonarCloud rule: "Random" objects should be reused, randoms
should not be recreated. This commit has taken all of the Randoms and made
them constant variables in the files that are using them.
* Switched to embedded Google checkstyle rules
Moved the configuration out of the execution to make it used in all
executions. Fixes#1016
* #1016: Moved checkstyle configuration back into execution
This refactoring may be better done in a new issue as it may have too
many implication.
* Replaced consoleOutput and failsOnError by failOnViolation
consoleOutput outputs everything while failsOnError just fails the build
but doesn't log the error. failOnViolation fails on a violation and logs
it (logViolationsToConsole defaults to true).
The missing class PreconditionViolationException is contained in
junit-platform-commons which comes in transitively by this JUnit
version. junit-jupiter-api had to be added because
spring-boot-dependencies imports an older version of this dependency.
* Fix issue #761: ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly
* Create leader election module
* Create Interface of Instance and MessageManager
* Create implementations with token ring algorithm
* Change package structure.
Create basic message system.
* Implement heartbeat and heartbeat invoking message system
* Implement election message handler
* Add leader message handler
* Add main entry point
* Add comments
* Update README.md
* Fix checkstyle issue
* Add Unit Tests
* Add Unit Tests
* Add bully leader selection
* Change System.out to log print.
Add MIT license in each file.
* Add More java doc comments
* Add unit test
* Add unit tests
* Add subclass-sandbox
* Add Unit Test
* Add Unit Test
* Fix Typo
* Move dependency into parent pom.xml
* Change local valuable reference to be var
The source directory was not working in the 2019.09 version of Eclipse. The
problem was in the layout of the project: after the src/main/java and
src/test/java, the directory was naed com.iluwatar.pipeline. It should've
been com/iluwatar/pipeline. This follows the hierarchy of all of the other
patterns.
Once these files were moved, the Pipeline project compiled without errors.
* 988: Took out the apache http component from root pom.xml
* 988: Updated the aggregator sub projects to use java.net.http instead of apache
* 988: Updated the api-gateway-service sub projects to use java.net.http instead of apache
* Applied the code style formatter
* #496 Add pipeline module to parent pom ✨
* #496: Add main application class and test for pipeline
* #496: Checkstyle format and add log messages on pipeline stages 🎨
* #496: Fill readme sections of pipeline ✨
* #496: Javadocs and checkstyle formatting 🎨
* #496: Follow PMD checks and add more explanation as block comment on App.java
* #496: Apply requested PR changes by iluwatar 🎨
* #970: Replace log4j usage on commander pattern to Slf4j API 🎨
* #970: Replace log4j usage on dao pattern to Slf4j API 🎨
* #970: Replace log4j usage on data mapper pattern to Slf4j API 🎨
* #970: Remove log4j dependency on data transfer object pom 🔥
* #970: Replace log4j usage on module pattern to Slf4j API 🎨
* #970: Replace log4j usage on serverless pattern to Slf4j API 🎨
This also removes the aws log4j dependency
* #970: Remove unnecessary gitignore line for log4j.xml 🔥
* #970: Remove remaining remnants of log4j 🔥
* #970: Replace System.out logging with appropriate logging methods 🎨
* #970: Replace System.out method references to Logger::info 🎨
* Moved java XML and annotations dependencies to project level instead
of as profiles
* Set compiler language level to 11
* Removed jdk8 from travis build
* Kept java level 8 in naked-objects/dom for datanucleus enhancer, for
now.
* Maven profiles to support jdk 11 builds. #948
Added maven profiles activated by jdk 11, wich will not break java 8 support.
Bumped lombok and datanucleus enhancer as the old versions dont work with 11.
* Fixed PMD issue when building naked-objects
* Fixed the eip modules with xml dependencies.
Previous dependency relaxing commit causes xml libs to go missing from
some modules that actually needed them
* Fix issue #761: ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly
* Create leader election module
* Create Interface of Instance and MessageManager
* Create implementations with token ring algorithm
* Change package structure.
Create basic message system.
* Implement heartbeat and heartbeat invoking message system
* Implement election message handler
* Add leader message handler
* Add main entry point
* Add comments
* Update README.md
* Fix checkstyle issue
* Add Unit Tests
* Add Unit Tests
* Add bully leader selection
* Change System.out to log print.
Add MIT license in each file.
* Add More java doc comments
* Add unit test
* Add unit tests
* #496 Add pipeline module to parent pom ✨
* #496: Add main application class and test for pipeline
* #496: Checkstyle format and add log messages on pipeline stages 🎨
* #496: Fill readme sections of pipeline ✨
* #496: Javadocs and checkstyle formatting 🎨
* #496: Follow PMD checks and add more explanation as block comment on App.java
* #496: Apply requested PR changes by iluwatar 🎨
* Fix for issue #954
Add javax.annotation and java.xml.bind as external maven dependencies
Verified with jdk-11
* Move dependency versions to main pom.xml's dependencyManagement section
* Upgrade maven plugins
* Upgrade maven plugins
Some general code cleanup was necessary due to upgrade of PMD and checkstyle.
Also needed to add Junit 4 as a dependency due to Mockito.timout issue found here:
https://github.com/mockito/mockito/issues/152
* 508 : Sonar qube critical Issue Fix
Refactor this method to reduce its Cognitive Complexity from 30 to the 15 allowed.
* 508: Sonar Qube Issue fxes
Define a constant instead of duplicating this literal " does not exist." 3 times.
* 508: sonar qube issue fixes
Define a constant instead of duplicating this literal "Some external api for only realtime execution could be called here." 3 times.
* master worker pattern
* Update App.java
* Adding new line to README.md
* Adding new line to pom.xml
* Adding new line to ArrayEquality.java
* Adding new line to Input.java
* Adding new line to Result.java
* Adding new line to ArrayTransposeMasterWorker.java
* Adding new line to ArrayTransposeMaster.java
* Adding new line to ArrayTransposeWorker.java
* Adding new line to Worker.java
* Adding new line to ArrayInputTest.java
* Adding new line ArrayTransposeMasterWorkerTest.java
* Adding new line to ArrayResult.java
* Review changes
* Update README.md
* Fixed wrong else condition
* Simplified creating Set of numbers
* Deleted unused imports
* Replaced 'for' loop with 'foreach' one
* Replaced explicit type with diamond
* Removed unnecesary brackets from lambda
* Removed unnecesary contains check before adding element to Set
* Fixed typo and changed non-english constant names
* Made minor changes in some patterns such as removed throws clause where not needed, changed incorrect order of arguments in assertEquals
* Minor refactorings and code style changes. 1) Removed several use of raw types 2) Removed unnecessary throws clauses 3) Used lambda expressions wherever applicable 4) Used apt assertion methods for readability 5) Use of try with resources wherever applicable 6) Corrected incorrect order of assertXXX arguments
* Removed unused import from Promise
* Addressed review comments
* Addressed checkstyle issue
* 1) Test cases were not stopping AudioService before ending test case 2) Changed Audio to be a good singleton, previously because of Audio being bad singleton, test cases which were using static methods could have caused intermittent failures. 3) Made some other refactorings as well
* Removed sonar issue and converted Audio to eager singleton for simplicity
* Updated class diagram PNG
* Resolves#643, test cases failed due to presence of global state in CallsCount. Because AppTest was executed before B2BServiceTest, it scheduled 1 sec timer using ThrottleTimerImpl class. While resetting it used that global CallCount class reset() method, which reset all counters. So that causes thread safety issue because of unintended sharing of application state between test cases, which is not a good practice.
* Updated class diagram png and added UCLS file
* 1) Updated test cases to use Junit Assert method as compared to assert keyword 2) Proper testing of RemoteService using RandomProvider interface. Introduced RandomProvider interface so that randomness can be controlled from test cases. 3) For readability used constant for representing FAILURE
* Addressing review comments, Deleting unintentional file and used FAILURE constant in ClientTest as well
Both output.txt and error.txt are produced by tests.
Each file contained a header that was overridden upon executing said
tests causing tracked files to be changed.
Added them to a local .gitignore file for this module.
[](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
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)
<br/>
# Introduction
Design patterns are formalized best practices that the programmer can use to
Design patterns are the best formalized practices a programmer can use to
solve common problems when designing an application or system.
Design patterns can speed up the development process by providing tested, proven
development paradigms.
Reusing design patterns helps to prevent subtle issues that can cause major
Reusing design patterns help prevent subtle issues that cause major
problems, and it also improves code readability for coders and architects who
are familiar with the patterns.
# Getting started
This site showcases Java Design Patterns. The solutions have been developed by
experienced programmers and architects from the open source community. The
patterns can be browsed by their high level descriptions or by looking at their
source code. The source code examples are well commented and can be thought as
programming tutorials on how to implement a specific pattern. We use the most
popular battle-proven open source Java technologies.
Before you dive into the material, you should be familiar with various
- Using pattern categories, `Creational`, `Behavioral` and others.
-Search for a specific pattern. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues).
-Search for a specific pattern by name. Can't find one? Please report a new pattern [here](https://github.com/iluwatar/java-design-patterns/issues).
- Using tags such as `Performance`, `Gang of Four` or `Data access`.
-Using pattern categories, `Creational`, `Behavioral`, and others.
Hopefully you find the object oriented solutions presented on this site useful
in your architectures and have as much fun learning them as we had developing them.
# How to contribute
If you are willing to contribute to the project you will find the relevant information in our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns).
If you are willing to contribute to the project you will find the relevant information in
our [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki). We will help
you and answer your questions in the [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns).
# License
This project is licensed under the terms of the MIT license.
# Contributors
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<tdalign="center"><ahref="https://sideris.xyz/"><imgsrc="https://avatars3.githubusercontent.com/u/5484694?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Petros G. Sideris</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/commits?author=sideris"title="Code">💻</a></td>
<tdalign="center"><ahref="https://github.com/Juaanma"><imgsrc="https://avatars3.githubusercontent.com/u/7390500?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Juan Manuel Suárez</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/commits?author=Juaanma"title="Code">💻</a></td>
<tdalign="center"><ahref="https://github.com/MSaifAsif"><imgsrc="https://avatars1.githubusercontent.com/u/6280554?v=4?s=100"width="100px;"alt=""/><br/><sub><b>M Saif Asif</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/commits?author=MSaifAsif"title="Code">💻</a></td>
<tdalign="center"><ahref="https://github.com/waisuan"><imgsrc="https://avatars2.githubusercontent.com/u/10975700?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Evan Sia Wai Suan</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/commits?author=waisuan"title="Code">💻</a></td>
<tdalign="center"><ahref="https://rachelcarmena.github.io"><imgsrc="https://avatars0.githubusercontent.com/u/22792183?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Rachel M. Carmena</b></sub></a><br/><ahref="#content-rachelcarmena"title="Content">🖋</a></td>
<tdalign="center"><ahref="http://www.edycutjong.com"><imgsrc="https://avatars1.githubusercontent.com/u/1098102?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Edy Cu Tjong</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/commits?author=edycutjong"title="Documentation">📖</a></td>
<tdalign="center"><ahref="https://ibrahimalii.github.io/"><imgsrc="https://avatars2.githubusercontent.com/u/21141301?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Ibrahim ali abdelghany</b></sub></a><br/><ahref="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AibrahimAlii"title="Reviewed Pull Requests">👀</a></td>
<tdalign="center"><ahref="https://github.com/JuanManuelAbate"><imgsrc="https://avatars.githubusercontent.com/u/16357060?v=4?s=100"width="100px;"alt=""/><br/><sub><b>Juan Manuel Abate</b></sub></a><br/><ahref="#translation-JuanManuelAbate"title="Translation">🌍</a></td>
Achieve flexibility of untyped languages and keep the type-safety
Use dynamic properties and achieve flexibility of untyped languages while keeping type-safety.
## Explanation
The Abstract Document pattern enables handling additional, non-static properties. This pattern
uses concept of traits to enable type safety and separate properties of different classes into
set of interfaces.
Real world example
> Consider a car that consists of multiple parts. However we don't know if the specific car really has all the parts, or just some of them. Our cars are dynamic and extremely flexible.
In plain words
> Abstract Document pattern allows attaching properties to objects without them knowing about it.
Wikipedia says
> An object-oriented structural design pattern for organizing objects in loosely typed key-value stores and exposing
the data using typed views. The purpose of the pattern is to achieve a high degree of flexibility between components
in a strongly typed language where new properties can be added to the object-tree on the fly, without losing the
support of type-safety. The pattern makes use of traits to separate different properties of a class into different
interfaces.
**Programmatic Example**
Let's first define the base classes `Document` and `AbstractDocument`. They basically make the object hold a property
* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf)
* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf)
* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492)
Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.
## Explanation
Real world example
> To create a kingdom we need objects with 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.
Real-world example
> 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
@ -32,47 +34,50 @@ Wikipedia says
**Programmatic Example**
Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the kingdom
Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the
kingdom.
```java
publicinterfaceCastle{
StringgetDescription();
}
publicinterfaceKing{
StringgetDescription();
}
publicinterfaceArmy{
StringgetDescription();
}
// Elven implementations ->
publicclassElfCastleimplementsCastle{
staticfinalStringDESCRIPTION="This is the Elven castle!";
staticfinalStringDESCRIPTION="This is the elven castle!";
@Override
publicStringgetDescription(){
returnDESCRIPTION;
}
}
publicclassElfKingimplementsKing{
staticfinalStringDESCRIPTION="This is the Elven king!";
staticfinalStringDESCRIPTION="This is the elven king!";
@Override
publicStringgetDescription(){
returnDESCRIPTION;
}
}
publicclassElfArmyimplementsArmy{
staticfinalStringDESCRIPTION="This is the Elven Army!";
staticfinalStringDESCRIPTION="This is the elven Army!";
@Override
publicStringgetDescription(){
returnDESCRIPTION;
}
}
// Orcish implementations similarly...
// Orcish implementations similarly -> ...
```
Then we have the abstraction and implementations for the kingdom factory
Then we have the abstraction and implementations for the kingdom factory.
```java
publicinterfaceKingdomFactory{
@ -106,21 +111,29 @@ 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
KingdomFactoryfactory=newElfKingdomFactory();
Castlecastle=factory.createCastle();
Kingking=factory.createKing();
Armyarmy=factory.createArmy();
varfactory=newElfKingdomFactory();
varcastle=factory.createCastle();
varking=factory.createKing();
vararmy=factory.createArmy();
castle.getDescription();// Output: This is the Elven castle!
king.getDescription();// Output: This is the Elven king!
army.getDescription();// Output: This is the Elven Army!
castle.getDescription();
king.getDescription();
army.getDescription();
```
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).
Program output:
```java
Thisistheelvencastle!
Thisistheelvenking!
ThisistheelvenArmy!
```
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
@ -143,7 +156,7 @@ public static class FactoryMaker {
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
> "The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes"
<br/>
* In plain words:
* A factory that groups individual but related/dependent factories together without specifying their concrete classes;
* A factory of factories;
---
# Example
* In a factory that creates kingdoms, we need objects with common theme:
* Elven kingdom needs an Elven king, Elven castle and Elven army;
* Orcish kingdom needs an Orcish king, Orcish castle and Orcish army;
<br/>
* There is a dependency between the objects in the kingdom;
---
# Diagram
* Based on the kingdom example, the diagram below showcases the different concrete factories and their concrete products:
.center[]
---
# Diagram
* The class diagram below showcases the factory of factories;
* At runtime, we can define which Kingdom type is needed and pass it as a parameter to define which concrete KingdomFactory to instantiate;
* The concrete factory returned will then be able to produce the related objects of the specified type;
.center[]
---
# Applicability
Use the Abstract Factory pattern when:
* A system should be independent of how its products are created, composed and represented;
* A system should be configured with one of multiple families of products;
* A 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;
---
# Applicability
Use the Abstract Factory pattern when:
* The lifetime of the dependency is conceptually shorter than the lifetime of the consumer;
* You need a run-time value to construct a particular dependency;
* You want to decide which product to call from a family at runtime;
* You need to supply one or more parameters only known at run-time before you can resolve a dependency;
---
#Use Cases
* Selecting to call the appropriate implementation of FileSystemAcmeService or DatabaseAcmeService or NetworkAcmeService at runtime;
* Unit test case writing becomes much easier;
---
# Consequences
* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
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
The class that implements the active object pattern will contain a self-synchronization mechanism without using 'synchronized' methods.
Real-world example
>The Orcs are known for their wildness and untameable soul. It seems like they have their own thread of control based on previous behavior.
To implement a creature that has its own thread of control mechanism and expose its API only and not the execution itself, we can use the Active Object pattern.
Allow new functions to be added to existing class hierarchies without affecting those hierarchies, and without creating the troublesome dependency cycles that are inherent to the GOF VISITOR Pattern.
## Applicability
This pattern can be used:
* When you need to add a new function to an existing hierarchy without the need to alter or affect that hierarchy.
* When there are functions that operate upon a hierarchy, but which do not belong in the hierarchy itself. e.g. the ConfigureForDOS / ConfigureForUnix / ConfigureForX issue.
* When you need to perform very different operations on an object depending upon its type.
@ -23,17 +139,23 @@ This pattern can be used:
* When the recompilation, relinking, retesting or redistribution of the derivatives of Element is very expensive.
## Consequences
The good:
* No dependency cycles between class hierarchies.
* No need to recompile all the visitors if a new one is added.
* Does not cause compilation failure in existing visitors if class hierarchy has a new member.
The bad:
* Violates the principle of least surprise or Liskov's Substitution principle by showing that it can accept all visitors but actually only being interested in particular visitors.
* Violates [Liskov's Substitution Principle](https://java-design-patterns.com/principles/#liskov-substitution-principle) by showing that it can accept all visitors but actually only being interested in particular visitors.
* Parallel hierarchy of visitors has to be created for all members in visitable class hierarchy.
Convert the interface of a class into another interface the clients
expect. Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that
couldn't otherwise because of incompatible interfaces.
## Explanation
Realworld example
Real-world example
> Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter.
> Another example would be the famous power adapter; a threelegged plug can't be connected to a twopronged outlet, it needs to use a power adapter that makes it compatible with the twopronged outlet.
> Consider that you have some pictures on your memory card and you need to transfer them to your computer. To transfer them, you need some kind of adapter that is compatible with your computer ports so that you can attach a memory card to your computer. In this case card reader is an adapter.
> Another example would be the famous power adapter; a three-legged plug can't be connected to a two-pronged outlet, it needs to use a power adapter that makes it compatible with the two-pronged outlets.
> Yet another example would be a translator translating words spoken by one person to another
In plain words
@ -38,15 +36,15 @@ Wikipedia says
Consider a captain that can only use rowing boats and cannot sail at all.
First we have interfaces `RowingBoat` and `FishingBoat`
First, we have interfaces `RowingBoat` and `FishingBoat`
And captain expects an implementation of `RowingBoat` interface to be able to move
```java
publicclassCaptainimplementsRowingBoat{
privateRowingBoatrowingBoat;
publicclassCaptain{
privatefinalRowingBoatrowingBoat;
// default constructor and setter for rowingBoat
publicCaptain(RowingBoatrowingBoat){
this.rowingBoat=rowingBoat;
}
@Override
publicvoidrow(){
rowingBoat.row();
}
}
```
Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.
Now let's say the pirates are coming and our captain needs to escape but there is only a fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.

## Applicability
Use the Adapter pattern when
*you want to use an existing class, and its interface does not match the one you need
*you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
*you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class.
*most of the applications using thirdparty 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.
*You want to use an existing class, and its interface does not match the one you need
*You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
*You need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. 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 won’t work when we want to adapt a class and all its subclasses.
*let’s Adapter override some of Adaptee’s behavior, since Adapter is a subclass of Adaptee.
*introduces only one object, and no additional pointer indirection is needed to get to the adaptee.
*Adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses.
*Let’s Adapter override some of Adaptee’s behavior since Adapter is a subclass of Adaptee.
*Introduces only one object, and no additional pointer indirection is needed to get to the adaptee.
An object adapter
*let’s a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.
*makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself.
*Lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.
*Makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making the Adapter refer to the subclass rather than the Adaptee itself.
* [Design Patterns: Elements of Reusable Object-Oriented Software](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612)
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)
* [Refactoring to Patterns](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60)
* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4)
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p/>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
*
* 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
@ -20,6 +20,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
packagecom.iluwatar.aggregator.microservices;
/**
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.