diff --git a/abstract-document/pom.xml b/abstract-document/pom.xml index ec1bd16dc633..020b04953b98 100644 --- a/abstract-document/pom.xml +++ b/abstract-document/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT abstract-document diff --git a/abstract-factory/pom.xml b/abstract-factory/pom.xml index 7e2613a0402f..5bbe3afa7951 100644 --- a/abstract-factory/pom.xml +++ b/abstract-factory/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT abstract-factory diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java index cecd8a894e68..be83cc315627 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test; /** - * Test for abstract factory + * Test for abstract factory. */ public class AbstractFactoryTest { diff --git a/acyclic-visitor/pom.xml b/acyclic-visitor/pom.xml index 9e59d1cef31f..55de9c7f9e4d 100644 --- a/acyclic-visitor/pom.xml +++ b/acyclic-visitor/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT acyclic-visitor diff --git a/adapter/pom.xml b/adapter/pom.xml index 4beedc26f85d..02b979ec9a5f 100644 --- a/adapter/pom.xml +++ b/adapter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT adapter diff --git a/aggregator-microservices/aggregator-service/pom.xml b/aggregator-microservices/aggregator-service/pom.xml index d6ebc823c307..5690c026a241 100644 --- a/aggregator-microservices/aggregator-service/pom.xml +++ b/aggregator-microservices/aggregator-service/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 aggregator-service diff --git a/aggregator-microservices/information-microservice/pom.xml b/aggregator-microservices/information-microservice/pom.xml index f20337be309b..f1d9d2dc0de8 100644 --- a/aggregator-microservices/information-microservice/pom.xml +++ b/aggregator-microservices/information-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/aggregator-microservices/inventory-microservice/pom.xml b/aggregator-microservices/inventory-microservice/pom.xml index b4d62606f38b..93ced9f686e1 100644 --- a/aggregator-microservices/inventory-microservice/pom.xml +++ b/aggregator-microservices/inventory-microservice/pom.xml @@ -29,7 +29,7 @@ aggregator-microservices com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 inventory-microservice diff --git a/aggregator-microservices/pom.xml b/aggregator-microservices/pom.xml index 7e4efa9f7b07..a63ec2f126a9 100644 --- a/aggregator-microservices/pom.xml +++ b/aggregator-microservices/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 aggregator-microservices diff --git a/ambassador/pom.xml b/ambassador/pom.xml index 0ab56632bce4..350cace6adeb 100644 --- a/ambassador/pom.xml +++ b/ambassador/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 ambassador diff --git a/api-gateway/api-gateway-service/pom.xml b/api-gateway/api-gateway-service/pom.xml index fa3e7286ba85..1be25c304665 100644 --- a/api-gateway/api-gateway-service/pom.xml +++ b/api-gateway/api-gateway-service/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 api-gateway-service diff --git a/api-gateway/image-microservice/pom.xml b/api-gateway/image-microservice/pom.xml index 06bd0b6e467d..bcbaeb539717 100644 --- a/api-gateway/image-microservice/pom.xml +++ b/api-gateway/image-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 image-microservice diff --git a/api-gateway/pom.xml b/api-gateway/pom.xml index 8ebf7a73f948..63a98699677c 100644 --- a/api-gateway/pom.xml +++ b/api-gateway/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 api-gateway diff --git a/api-gateway/price-microservice/pom.xml b/api-gateway/price-microservice/pom.xml index ad21da6831c8..47f16b4dd31f 100644 --- a/api-gateway/price-microservice/pom.xml +++ b/api-gateway/price-microservice/pom.xml @@ -29,7 +29,7 @@ api-gateway com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/async-method-invocation/pom.xml b/async-method-invocation/pom.xml index 6d118e74727a..62ec375dfad7 100644 --- a/async-method-invocation/pom.xml +++ b/async-method-invocation/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT async-method-invocation diff --git a/balking/pom.xml b/balking/pom.xml index 8d798ecb43a0..aca041684f50 100644 --- a/balking/pom.xml +++ b/balking/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/bridge/pom.xml b/bridge/pom.xml index 56b2b61f1fb3..b37cb8c9da27 100644 --- a/bridge/pom.xml +++ b/bridge/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT bridge diff --git a/builder/pom.xml b/builder/pom.xml index 3a8e6ccf0d85..e31ef2798bcf 100644 --- a/builder/pom.xml +++ b/builder/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT builder diff --git a/business-delegate/pom.xml b/business-delegate/pom.xml index 7c7313e8f3b8..4bf05843c00c 100644 --- a/business-delegate/pom.xml +++ b/business-delegate/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT business-delegate diff --git a/bytecode/pom.xml b/bytecode/pom.xml index ac60e9345dba..6b2f0bf548ee 100644 --- a/bytecode/pom.xml +++ b/bytecode/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/caching/pom.xml b/caching/pom.xml index fec70be733db..e479bc143b52 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT caching diff --git a/callback/pom.xml b/callback/pom.xml index 14c3462036a3..634e4f7e90c9 100644 --- a/callback/pom.xml +++ b/callback/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT callback diff --git a/chain/pom.xml b/chain/pom.xml index 4e5357b8d4f4..f92637935560 100644 --- a/chain/pom.xml +++ b/chain/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT chain diff --git a/circuit-breaker/README.md b/circuit-breaker/README.md index db75ca58c0d0..6a1c631c7cf7 100644 --- a/circuit-breaker/README.md +++ b/circuit-breaker/README.md @@ -1,6 +1,6 @@ --- layout: pattern -title: CircuitBreaker +title: Circuit Breaker folder: circuit-breaker permalink: /patterns/circuit-breaker/ categories: Other diff --git a/circuit-breaker/pom.xml b/circuit-breaker/pom.xml index 6ef7da2236a2..b04cd5c25ecc 100644 --- a/circuit-breaker/pom.xml +++ b/circuit-breaker/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT circuit-breaker diff --git a/collection-pipeline/README.md b/collection-pipeline/README.md index ab13b21dbb75..9d2f2693b910 100644 --- a/collection-pipeline/README.md +++ b/collection-pipeline/README.md @@ -3,7 +3,7 @@ layout: pattern title: Collection Pipeline folder: collection-pipeline permalink: /patterns/collection-pipeline/ -categories: Functional +categories: Other tags: - Java - Difficulty-Beginner diff --git a/collection-pipeline/pom.xml b/collection-pipeline/pom.xml index 0ab16f8259d1..3c2a925c4836 100644 --- a/collection-pipeline/pom.xml +++ b/collection-pipeline/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT collection-pipeline diff --git a/command/pom.xml b/command/pom.xml index d9fbd90d091d..d43e09822734 100644 --- a/command/pom.xml +++ b/command/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT command diff --git a/commander/README.md b/commander/README.md index 41e2cd587553..71ef7fe9c303 100644 --- a/commander/README.md +++ b/commander/README.md @@ -3,7 +3,7 @@ layout: pattern title: Commander folder: commander permalink: /patterns/commander/ -categories: +categories: Other tags: - Java - Difficulty-Intermediate diff --git a/commander/pom.xml b/commander/pom.xml index fbe45337707e..7c675a304d3a 100644 --- a/commander/pom.xml +++ b/commander/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT commander diff --git a/composite/pom.xml b/composite/pom.xml index fb16cae3af53..e833646807da 100644 --- a/composite/pom.xml +++ b/composite/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT composite diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 933d38bde313..235d1c31f097 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -37,6 +37,10 @@ public Word(List letters) { letters.forEach(this::add); } + /** + * Constructor. + * @param letters to include + */ public Word(char... letters) { for (char letter : letters) { this.add(new Letter(letter)); diff --git a/converter/README.md b/converter/README.md index 79b539422892..5cde646eedbc 100644 --- a/converter/README.md +++ b/converter/README.md @@ -17,6 +17,71 @@ mapping, reducing a boilerplate code to minimum. ![alt text](./etc/converter.png "Converter Pattern") +## Explanation + +Real world example + +> In real world applications it is often the case that database layer consists of entities that need to be mapped into DTOs for use on the business logic layer. Similar mapping is done for potentially huge amount of classes and we need a generic way to achieve this. + +In plain words + +> Converter pattern makes it easy to map instances of one class into instances of another class. + +**Programmatic Example** + +We need a generic solution for the mapping problem. To achieve this, let's introduce a generic converter. + +```java +public class Converter { + + private final Function fromDto; + private final Function fromEntity; + + public Converter(final Function fromDto, final Function fromEntity) { + this.fromDto = fromDto; + this.fromEntity = fromEntity; + } + + public final U convertFromDto(final T dto) { + return fromDto.apply(dto); + } + + public final T convertFromEntity(final U entity) { + return fromEntity.apply(entity); + } + + public final List createFromDtos(final Collection dtos) { + return dtos.stream().map(this::convertFromDto).collect(Collectors.toList()); + } + + public final List createFromEntities(final Collection entities) { + return entities.stream().map(this::convertFromEntity).collect(Collectors.toList()); + } +} +``` + +The specialized converters inherit from this base class as follows. + +```java +public class UserConverter extends Converter { + + public UserConverter() { + super(userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + userDto.getEmail()), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getUserId())); + } +} +``` + +Now mapping between User and UserDto becomes trivial. + +```java +Converter userConverter = new UserConverter(); +UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); +User user = userConverter.convertFromDto(dtoUser); +``` + ## Applicability Use the Converter Pattern in the following situations: diff --git a/converter/pom.xml b/converter/pom.xml index 6c900efc3305..9495e811ec9a 100644 --- a/converter/pom.xml +++ b/converter/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/cqrs/pom.xml b/cqrs/pom.xml index feab9d1acacb..0f1b4a7c31d9 100644 --- a/cqrs/pom.xml +++ b/cqrs/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT cqrs diff --git a/dao/pom.xml b/dao/pom.xml index 5d6bc94546fa..c3bc3300c030 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT dao diff --git a/data-bus/pom.xml b/data-bus/pom.xml index 230fe6b84bde..9a13745fe159 100644 --- a/data-bus/pom.xml +++ b/data-bus/pom.xml @@ -33,7 +33,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT data-bus diff --git a/data-locality/pom.xml b/data-locality/pom.xml index 12c0f4f185e6..d64b0f9416ff 100644 --- a/data-locality/pom.xml +++ b/data-locality/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT data-locality diff --git a/data-mapper/pom.xml b/data-mapper/pom.xml index 7da70f8fd243..b587960ef788 100644 --- a/data-mapper/pom.xml +++ b/data-mapper/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT data-mapper diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml index ebdb15afa3dd..d01ff4f72ec0 100644 --- a/data-transfer-object/pom.xml +++ b/data-transfer-object/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT data-transfer-object diff --git a/decorator/pom.xml b/decorator/pom.xml index 9b9ae0548602..3d005fa64a0a 100644 --- a/decorator/pom.xml +++ b/decorator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT decorator diff --git a/delegation/pom.xml b/delegation/pom.xml index c7ceea6c0c48..5179a86852cd 100644 --- a/delegation/pom.xml +++ b/delegation/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index fd9584ed2ac8..5caf8fbbce4f 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT dependency-injection diff --git a/dirty-flag/pom.xml b/dirty-flag/pom.xml index a044ad4d1e07..0362780cb1e2 100644 --- a/dirty-flag/pom.xml +++ b/dirty-flag/pom.xml @@ -29,11 +29,11 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT com.iluwatar dirty-flag - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT dirty-flag http://maven.apache.org diff --git a/double-buffer/README.md b/double-buffer/README.md index 8e8e7acf6bfd..9cd5ebfa8420 100644 --- a/double-buffer/README.md +++ b/double-buffer/README.md @@ -1,4 +1,3 @@ - --- layout: pattern title: Double Buffer diff --git a/double-buffer/pom.xml b/double-buffer/pom.xml index a904c58842ef..f4ea7db792a3 100644 --- a/double-buffer/pom.xml +++ b/double-buffer/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml index 02b03b7733f4..27d7d24205d2 100644 --- a/double-checked-locking/pom.xml +++ b/double-checked-locking/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT double-checked-locking diff --git a/double-dispatch/pom.xml b/double-dispatch/pom.xml index 0884d29c2164..059a7515b3b5 100644 --- a/double-dispatch/pom.xml +++ b/double-dispatch/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT double-dispatch diff --git a/eip-aggregator/pom.xml b/eip-aggregator/pom.xml index e4b96d0aa75d..e32969eaec76 100644 --- a/eip-aggregator/pom.xml +++ b/eip-aggregator/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/eip-message-channel/pom.xml b/eip-message-channel/pom.xml index 5e72da9ef32e..800a62883c18 100644 --- a/eip-message-channel/pom.xml +++ b/eip-message-channel/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT eip-message-channel diff --git a/eip-publish-subscribe/pom.xml b/eip-publish-subscribe/pom.xml index 150490a7f0da..65384438ef44 100644 --- a/eip-publish-subscribe/pom.xml +++ b/eip-publish-subscribe/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT eip-publish-subscribe diff --git a/eip-splitter/pom.xml b/eip-splitter/pom.xml index 6aef2dc09953..e73139b959fb 100644 --- a/eip-splitter/pom.xml +++ b/eip-splitter/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/eip-wire-tap/pom.xml b/eip-wire-tap/pom.xml index ae896f0d0399..6d29aac1afd7 100644 --- a/eip-wire-tap/pom.xml +++ b/eip-wire-tap/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/event-aggregator/pom.xml b/event-aggregator/pom.xml index 191eaed043e0..a9e8b4cd16ff 100644 --- a/event-aggregator/pom.xml +++ b/event-aggregator/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT event-aggregator diff --git a/event-asynchronous/pom.xml b/event-asynchronous/pom.xml index 227c70a2afe3..c05f54afde3f 100644 --- a/event-asynchronous/pom.xml +++ b/event-asynchronous/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT event-asynchronous diff --git a/event-driven-architecture/pom.xml b/event-driven-architecture/pom.xml index 13217786ac36..62a00fb70a5d 100644 --- a/event-driven-architecture/pom.xml +++ b/event-driven-architecture/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT event-driven-architecture diff --git a/event-queue/pom.xml b/event-queue/pom.xml index 74f467a4847a..58f31e3a05cb 100644 --- a/event-queue/pom.xml +++ b/event-queue/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT event-queue diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml index 0b9c93770639..1232bb4b43fe 100644 --- a/event-sourcing/pom.xml +++ b/event-sourcing/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT event-sourcing diff --git a/execute-around/pom.xml b/execute-around/pom.xml index 1fc4125f3220..e4f1d3fd299f 100644 --- a/execute-around/pom.xml +++ b/execute-around/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT execute-around diff --git a/extension-objects/pom.xml b/extension-objects/pom.xml index 7eb914e3ec9c..34630508f480 100644 --- a/extension-objects/pom.xml +++ b/extension-objects/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/facade/pom.xml b/facade/pom.xml index 9c68490a63f5..560f7ae1018c 100644 --- a/facade/pom.xml +++ b/facade/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT facade diff --git a/factory-kit/pom.xml b/factory-kit/pom.xml index 03e5e822347a..194f94d5d926 100644 --- a/factory-kit/pom.xml +++ b/factory-kit/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT factory-kit diff --git a/factory-method/pom.xml b/factory-method/pom.xml index f4ca2cd5048b..5b3b6c9cc5b1 100644 --- a/factory-method/pom.xml +++ b/factory-method/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT factory-method diff --git a/feature-toggle/pom.xml b/feature-toggle/pom.xml index 7215eaf0083e..4ecd5f59df29 100644 --- a/feature-toggle/pom.xml +++ b/feature-toggle/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/fluentinterface/pom.xml b/fluentinterface/pom.xml index 1e76ea628f9d..a40541fc4e2b 100644 --- a/fluentinterface/pom.xml +++ b/fluentinterface/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/flux/pom.xml b/flux/pom.xml index 324e4499544b..1c44d80574ec 100644 --- a/flux/pom.xml +++ b/flux/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT flux diff --git a/flyweight/pom.xml b/flyweight/pom.xml index 04b153be8ffb..a17b43dcd572 100644 --- a/flyweight/pom.xml +++ b/flyweight/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT flyweight diff --git a/front-controller/pom.xml b/front-controller/pom.xml index 1f6e1a7f661a..de0f084a9aa2 100644 --- a/front-controller/pom.xml +++ b/front-controller/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT front-controller diff --git a/game-loop/README.md b/game-loop/README.md new file mode 100644 index 000000000000..5df86e045866 --- /dev/null +++ b/game-loop/README.md @@ -0,0 +1,40 @@ +--- +layout: pattern +title: Game Loop +folder: game-loop +permalink: /patterns/game-loop/ +categories: Other +tags: + - Java + - Difficulty-Beginner +--- + +## Intent +A game loop runs continuously during gameplay. Each turn of the loop, it processes user input without blocking, updates the game state, and renders the game. It tracks the passage of time to control the rate of gameplay. + +This pattern decouple the progression of game time from user input and processor speed. + +## Applicability +This pattern is used in every game engine. + +## Explanation +Game loop is the main process of all the game rendering threads. It drives input process, internal status update, rendering, AI and all the other processes. + +There are a lot of implementations of game loop: + +- Frame-based game loop + +Frame-based game loop is the easiest implementation. The loop always keeps spinning for the following three processes: processInput, update and render. The problem with it is you have no control over how fast the game runs. On a fast machine, that loop will spin so fast users won’t be able to see what’s going on. On a slow machine, the game will crawl. If you have a part of the game that’s content-heavy or does more AI or physics, the game will actually play slower there. + +- Variable-step game loop + +The variable-step game loop chooses a time step to advance based on how much real time passed since the last frame. The longer the frame takes, the bigger steps the game takes. It always keeps up with real time because it will take bigger and bigger steps to get there. + +- Fixed-step game loop + +For fixed-step game loop, a certain amount of real time has elapsed since the last turn of the game loop. This is how much game time need to be simulated for the game’s “now” to catch up with the player’s. + + +## Credits + +* [Game Programming Patterns - Game Loop](http://gameprogrammingpatterns.com/game-loop.html) \ No newline at end of file diff --git a/game-loop/pom.xml b/game-loop/pom.xml new file mode 100644 index 000000000000..da5c2bb09bc0 --- /dev/null +++ b/game-loop/pom.xml @@ -0,0 +1,45 @@ + + + + + java-design-patterns + com.iluwatar + 1.23.0-SNAPSHOT + + 4.0.0 + + game-loop + + + junit + junit + + + + + \ No newline at end of file diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/App.java b/game-loop/src/main/java/com/iluwatar/gameloop/App.java new file mode 100644 index 000000000000..4d9e4c11dfde --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/App.java @@ -0,0 +1,76 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A game loop runs continuously during gameplay. Each turn of the loop, it processes + * user input without blocking, updates the game state, and renders the game. It tracks + * the passage of time to control the rate of gameplay. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + + /** + * Each type of game loop will run for 2 seconds. + */ + private static final int GAME_LOOP_DURATION_TIME = 2000; + + /** + * Program entry point. + * @param args runtime arguments + */ + public static void main(String[] args) { + + try { + LOGGER.info("Start frame-based game loop:"); + var frameBasedGameLoop = new FrameBasedGameLoop(); + frameBasedGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + frameBasedGameLoop.stop(); + LOGGER.info("Stop frame-based game loop."); + + LOGGER.info("Start variable-step game loop:"); + var variableStepGameLoop = new VariableStepGameLoop(); + variableStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + variableStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + LOGGER.info("Start fixed-step game loop:"); + var fixedStepGameLoop = new FixedStepGameLoop(); + fixedStepGameLoop.run(); + Thread.sleep(GAME_LOOP_DURATION_TIME); + fixedStepGameLoop.stop(); + LOGGER.info("Stop variable-step game loop."); + + } catch (InterruptedException e) { + LOGGER.error(e.getMessage()); + } + } + +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java new file mode 100644 index 000000000000..69b93bc74846 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/Bullet.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * Bullet object class. + */ +public class Bullet { + + private float position; + + public Bullet() { + position = 0.0f; + } + + public float getPosition() { + return position; + } + + public void setPosition(float position) { + this.position = position; + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java new file mode 100644 index 000000000000..07ad21584ea7 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FixedStepGameLoop.java @@ -0,0 +1,62 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * For fixed-step game loop, a certain amount of real time has elapsed since the + * last turn of the game loop. This is how much game time need to be simulated for + * the game’s “now” to catch up with the player’s. + */ +public class FixedStepGameLoop extends GameLoop { + + /** + * 20 ms per frame = 50 FPS. + */ + private static final long MS_PER_FRAME = 20; + + @Override + protected void processGameLoop() { + var previousTime = System.currentTimeMillis(); + var lag = 0L; + while (isGameRunning()) { + var currentTime = System.currentTimeMillis(); + var elapsedTime = currentTime - previousTime; + previousTime = currentTime; + lag += elapsedTime; + + processInput(); + + while (lag >= MS_PER_FRAME) { + update(); + lag -= MS_PER_FRAME; + } + + render(); + } + } + + protected void update() { + controller.moveBullet(0.5f * MS_PER_FRAME / 1000); + } +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java new file mode 100644 index 000000000000..45c59168ffd3 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/FrameBasedGameLoop.java @@ -0,0 +1,53 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * Frame-based game loop is the easiest implementation. The loop always keeps spinning + * for the following three processes: processInput, update and render. The problem with + * it is you have no control over how fast the game runs. On a fast machine, that loop + * will spin so fast users won’t be able to see what’s going on. On a slow machine, the + * game will crawl. If you have a part of the game that’s content-heavy or does more AI + * or physics, the game will actually play slower there. + */ +public class FrameBasedGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + while (isGameRunning()) { + processInput(); + update(); + render(); + } + } + + /** + * Each time when update() is invoked, a new frame is created, and the bullet will be + * moved 0.5f away from the current position. + */ + protected void update() { + controller.moveBullet(0.5f); + } + +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java new file mode 100644 index 000000000000..00c65332b4ce --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameController.java @@ -0,0 +1,61 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * Update and render objects in the game. Here we add a Bullet object to the + * game system to show how the game loop works. + */ +public class GameController { + + protected final Bullet bullet; + + /** + * Initialize Bullet instance. + */ + public GameController() { + bullet = new Bullet(); + } + + /** + * Move bullet position by the provided offset. + * + * @param offset moving offset + */ + public void moveBullet(float offset) { + var currentPosition = bullet.getPosition(); + bullet.setPosition(currentPosition + offset); + } + + /** + * Get current position of the bullet. + * + * @return position of bullet + */ + public float getBulletPosition() { + return bullet.getPosition(); + } + +} + diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java new file mode 100644 index 000000000000..47410382203e --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java @@ -0,0 +1,104 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import java.util.Random; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract class for GameLoop implementation class. + */ +public abstract class GameLoop { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected volatile GameStatus status; + + protected GameController controller; + + private Thread gameThread; + + /** + * Initialize game status to be stopped. + */ + public GameLoop() { + controller = new GameController(); + status = GameStatus.STOPPED; + } + + /** + * Run game loop. + */ + public void run() { + status = GameStatus.RUNNING; + gameThread = new Thread(() -> processGameLoop()); + gameThread.start(); + } + + /** + * Stop game loop. + */ + public void stop() { + status = GameStatus.STOPPED; + } + + /** + * Check if game is running or not. + * + * @return {@code true} if the game is running. + */ + public boolean isGameRunning() { + return status == GameStatus.RUNNING ? true : false; + } + + /** + * Handle any user input that has happened since the last call. In order to + * simulate the situation in real-life game, here we add a random time lag. + * The time lag ranges from 50 ms to 250 ms. + */ + protected void processInput() { + try { + int lag = new Random().nextInt(200) + 50; + Thread.sleep(lag); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + + /** + * Render game frames to screen. Here we print bullet position to simulate + * this process. + */ + protected void render() { + var position = controller.getBulletPosition(); + logger.info("Current bullet position: " + position); + } + + /** + * execute game loop logic. + */ + protected abstract void processGameLoop(); + +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java new file mode 100644 index 000000000000..46d90669e498 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java @@ -0,0 +1,33 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * Enum class for game status. + */ +public enum GameStatus { + + RUNNING, STOPPED + +} diff --git a/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java new file mode 100644 index 000000000000..544590c5bd98 --- /dev/null +++ b/game-loop/src/main/java/com/iluwatar/gameloop/VariableStepGameLoop.java @@ -0,0 +1,51 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +/** + * The variable-step game loop chooses a time step to advance based on how much + * real time passed since the last frame. The longer the frame takes, the bigger + * steps the game takes. It always keeps up with real time because it will take + * bigger and bigger steps to get there. + */ +public class VariableStepGameLoop extends GameLoop { + + @Override + protected void processGameLoop() { + var lastFrameTime = System.currentTimeMillis(); + while (isGameRunning()) { + processInput(); + var currentFrameTime = System.currentTimeMillis(); + var elapsedTime = currentFrameTime - lastFrameTime; + update(elapsedTime); + lastFrameTime = currentFrameTime; + render(); + } + } + + protected void update(Long elapsedTime) { + controller.moveBullet(0.5f * elapsedTime / 1000); + } + +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java new file mode 100644 index 000000000000..187fe1537c97 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/AppTest.java @@ -0,0 +1,39 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.junit.Test; + +/** + * App unit test class. + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + new App().main(args); + } + +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java new file mode 100644 index 000000000000..5c8614fa1318 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FixedStepGameLoopTest.java @@ -0,0 +1,54 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * FixedStepGameLoop unit test class. + */ +public class FixedStepGameLoopTest { + + private FixedStepGameLoop gameLoop; + + @Before + public void setup() { + gameLoop = new FixedStepGameLoop(); + } + + @After + public void tearDown() { + gameLoop = null; + } + + @Test + public void testUpdate() { + gameLoop.update(); + Assert.assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); + } + +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java new file mode 100644 index 000000000000..e8eb922dcd3d --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/FrameBasedGameLoopTest.java @@ -0,0 +1,53 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * FrameBasedGameLoop unit test class. + */ +public class FrameBasedGameLoopTest { + + private FrameBasedGameLoop gameLoop; + + @Before + public void setup() { + gameLoop = new FrameBasedGameLoop(); + } + + @After + public void tearDown() { + gameLoop = null; + } + + @Test + public void testUpdate() { + gameLoop.update(); + Assert.assertEquals(0.5f, gameLoop.controller.getBulletPosition(), 0); + } +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java new file mode 100644 index 000000000000..3d057d830440 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameControllerTest.java @@ -0,0 +1,56 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class GameControllerTest { + + private GameController controller; + + @Before + public void setup() { + controller = new GameController(); + } + + @After + public void tearDown() { + controller = null; + } + + @Test + public void testMoveBullet() { + controller.moveBullet(1.5f); + Assert.assertEquals(1.5f, controller.bullet.getPosition(), 0); + } + + @Test + public void testGetBulletPosition() { + Assert.assertEquals(controller.bullet.getPosition(), controller.getBulletPosition(), 0); + } + +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java new file mode 100644 index 000000000000..61e2a3bb6ce0 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/GameLoopTest.java @@ -0,0 +1,71 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * GameLoop unit test class. + */ +public class GameLoopTest { + + private GameLoop gameLoop; + + /** + * Create mock implementation of GameLoop. + */ + @Before + public void setup() { + gameLoop = new GameLoop() { + @Override + protected void processGameLoop() {} + }; + } + + @After + public void tearDown() { + gameLoop = null; + } + + @Test + public void testRun() { + gameLoop.run(); + Assert.assertEquals(GameStatus.RUNNING, gameLoop.status); + } + + @Test + public void testStop() { + gameLoop.stop(); + Assert.assertEquals(GameStatus.STOPPED, gameLoop.status); + } + + @Test + public void testIsGameRunning() { + Assert.assertEquals(false, gameLoop.isGameRunning()); + } + +} diff --git a/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java new file mode 100644 index 000000000000..43dd4f732426 --- /dev/null +++ b/game-loop/src/test/java/com/iluwatar/gameloop/VariableStepGameLoopTest.java @@ -0,0 +1,54 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.gameloop; + +import java.lang.reflect.InvocationTargetException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * VariableStepGameLoop unit test class. + */ +public class VariableStepGameLoopTest { + + private VariableStepGameLoop gameLoop; + + @Before + public void setup() { + gameLoop = new VariableStepGameLoop(); + } + + @After + public void tearDown() { + gameLoop = null; + } + + @Test + public void testUpdate() { + gameLoop.update(20L); + Assert.assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0); + } +} diff --git a/guarded-suspension/pom.xml b/guarded-suspension/pom.xml index b594a2b71108..bc1dec09eedc 100644 --- a/guarded-suspension/pom.xml +++ b/guarded-suspension/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT jar guarded-suspension diff --git a/half-sync-half-async/pom.xml b/half-sync-half-async/pom.xml index 462d4ab0d3c8..3e86d3a173b2 100644 --- a/half-sync-half-async/pom.xml +++ b/half-sync-half-async/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT half-sync-half-async diff --git a/hexagonal/pom.xml b/hexagonal/pom.xml index 060d0135b428..324b9c8b8bf6 100644 --- a/hexagonal/pom.xml +++ b/hexagonal/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT hexagonal diff --git a/intercepting-filter/pom.xml b/intercepting-filter/pom.xml index bff125ee68cc..acc9f2268cfb 100644 --- a/intercepting-filter/pom.xml +++ b/intercepting-filter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT intercepting-filter diff --git a/interpreter/pom.xml b/interpreter/pom.xml index 311df2fe356f..1789069f757a 100644 --- a/interpreter/pom.xml +++ b/interpreter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT interpreter diff --git a/iterator/pom.xml b/iterator/pom.xml index 7f8b120ec3e4..a1f1b29100ec 100644 --- a/iterator/pom.xml +++ b/iterator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT iterator diff --git a/layers/pom.xml b/layers/pom.xml index 1e018c3a2ea3..0627fdf9b103 100644 --- a/layers/pom.xml +++ b/layers/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT com.iluwatar.layers layers diff --git a/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java index 403816421a4b..885852519aba 100644 --- a/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java +++ b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java @@ -23,12 +23,12 @@ package com.iluwatar.layers.service; -import com.iluwatar.layers.dto.CakeInfo; -import com.iluwatar.layers.dto.CakeLayerInfo; -import com.iluwatar.layers.dto.CakeToppingInfo; import com.iluwatar.layers.dao.CakeDao; import com.iluwatar.layers.dao.CakeLayerDao; import com.iluwatar.layers.dao.CakeToppingDao; +import com.iluwatar.layers.dto.CakeInfo; +import com.iluwatar.layers.dto.CakeLayerInfo; +import com.iluwatar.layers.dto.CakeToppingInfo; import com.iluwatar.layers.entity.Cake; import com.iluwatar.layers.entity.CakeLayer; import com.iluwatar.layers.entity.CakeTopping; @@ -40,7 +40,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Service; diff --git a/lazy-loading/pom.xml b/lazy-loading/pom.xml index d52c14a42f45..c0245aac018a 100644 --- a/lazy-loading/pom.xml +++ b/lazy-loading/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT lazy-loading diff --git a/leader-election/pom.xml b/leader-election/pom.xml index 725942e2adb2..9e94ce32f241 100644 --- a/leader-election/pom.xml +++ b/leader-election/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT leader-election diff --git a/marker/pom.xml b/marker/pom.xml index d8166ab86c32..fa794b5959da 100644 --- a/marker/pom.xml +++ b/marker/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/marker/src/main/java/App.java b/marker/src/main/java/App.java index 93697e6ebf40..384c999dc52d 100644 --- a/marker/src/main/java/App.java +++ b/marker/src/main/java/App.java @@ -25,27 +25,23 @@ import org.slf4j.LoggerFactory; /** - * Created by Alexis on 28-Apr-17. - * With Marker interface idea is to make empty interface and extend it. - * Basically it is just to identify the special objects from normal objects. - * Like in case of serialization , objects that need to be serialized must implement serializable interface - * (it is empty interface) and down the line writeObject() method must be checking - * if it is a instance of serializable or not. - *

- * Marker interface vs annotation - * Marker interfaces and marker annotations both have their uses, - * neither of them is obsolete or always better then the other one. - * If you want to define a type that does not have any new methods associated with it, - * a marker interface is the way to go. - * If you want to mark program elements other than classes and interfaces, - * to allow for the possibility of adding more information to the marker in the future, - * or to fit the marker into a framework that already makes heavy use of annotation types, - * then a marker annotation is the correct choice + * Created by Alexis on 28-Apr-17. With Marker interface idea is to make empty interface and extend + * it. Basically it is just to identify the special objects from normal objects. Like in case of + * serialization , objects that need to be serialized must implement serializable interface (it is + * empty interface) and down the line writeObject() method must be checking if it is a instance of + * serializable or not. + * + *

Marker interface vs annotation Marker interfaces and marker annotations both have their uses, + * neither of them is obsolete or always better then the other one. If you want to define a type + * that does not have any new methods associated with it, a marker interface is the way to go. If + * you want to mark program elements other than classes and interfaces, to allow for the possibility + * of adding more information to the marker in the future, or to fit the marker into a framework + * that already makes heavy use of annotation types, then a marker annotation is the correct choice */ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/marker/src/main/java/Guard.java b/marker/src/main/java/Guard.java index d135d54598f4..9a57e15fdfb3 100644 --- a/marker/src/main/java/Guard.java +++ b/marker/src/main/java/Guard.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; /** - * Class defining Guard + * Class defining Guard. */ public class Guard implements Permission { diff --git a/marker/src/main/java/Permission.java b/marker/src/main/java/Permission.java index e1b45e99f7f4..5395ccadf9a1 100644 --- a/marker/src/main/java/Permission.java +++ b/marker/src/main/java/Permission.java @@ -22,8 +22,7 @@ */ /** - * Interface without any methods - * Marker interface is based on that assumption + * Interface without any methods Marker interface is based on that assumption. */ public interface Permission { } diff --git a/marker/src/main/java/Thief.java b/marker/src/main/java/Thief.java index 155a974c19d3..341eae3777d9 100644 --- a/marker/src/main/java/Thief.java +++ b/marker/src/main/java/Thief.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; /** - * Class defining Thief + * Class defining Thief. */ public class Thief { diff --git a/master-worker-pattern/README.md b/master-worker-pattern/README.md index 4d2aa0e38d95..f8b5509369ff 100644 --- a/master-worker-pattern/README.md +++ b/master-worker-pattern/README.md @@ -3,7 +3,7 @@ layout: pattern title: Master-Worker folder: master-worker-pattern permalink: /patterns/master-worker-pattern/ -categories: Centralised Parallel Processing +categories: Other tags: - Java - Difficulty-Intermediate diff --git a/master-worker-pattern/pom.xml b/master-worker-pattern/pom.xml index 8ce79ed7f7c5..7ace130d8a9e 100644 --- a/master-worker-pattern/pom.xml +++ b/master-worker-pattern/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT master-worker-pattern diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java index e3ffd08c4d44..b8036b91199a 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/App.java @@ -28,30 +28,37 @@ import org.slf4j.LoggerFactory; /** - *

The Master-Worker pattern is used when the problem at hand can be solved by dividing into - * multiple parts which need to go through the same computation and may need to be aggregated to get final result. - * Parallel processing is performed using a system consisting of a master and some number of workers, where a - * master divides the work among the workers, gets the result back from them and assimilates all the results to - * give final result. The only communication is between the master and the worker - none of the workers communicate - * among one another and the user only communicates with the master to get required job done.

- *

In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and {@link Worker} which - * have to be extended by the classes which will perform the specific job at hand (in this case finding transpose of - * matrix, done by {@link ArrayTransposeMasterWorker}, {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). - * The Master class divides the work into parts to be given to the workers, collects the results from the workers and - * aggregates it when all workers have responded before returning the solution. The Worker class extends the Thread - * class to enable parallel processing, and does the work once the data has been received from the Master. The - * MasterWorker contains a reference to the Master class, gets the input from the App and passes it on to the Master. - * These 3 classes define the system which computes the result. We also have 2 abstract classes {@link Input} and - * {@link Result}, which contain the input data and result data respectively. The Input class also has an abstract - * method divideData which defines how the data is to be divided into segments. These classes are extended by - * {@link ArrayInput} and {@link ArrayResult}.

+ *

The Master-Worker pattern is used when the problem at hand can be solved by + * dividing into + * multiple parts which need to go through the same computation and may need to be aggregated to get + * final result. Parallel processing is performed using a system consisting of a master and some + * number of workers, where a master divides the work among the workers, gets the result back from + * them and assimilates all the results to give final result. The only communication is between the + * master and the worker - none of the workers communicate among one another and the user only + * communicates with the master to get required job done.

+ *

In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and + * {@link Worker} which + * have to be extended by the classes which will perform the specific job at hand (in this case + * finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, {@link + * ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work into + * parts to be given to the workers, collects the results from the workers and aggregates it when + * all workers have responded before returning the solution. The Worker class extends the Thread + * class to enable parallel processing, and does the work once the data has been received from the + * Master. The MasterWorker contains a reference to the Master class, gets the input from the App + * and passes it on to the Master. These 3 classes define the system which computes the result. We + * also have 2 abstract classes {@link Input} and {@link Result}, which contain the input data and + * result data respectively. The Input class also has an abstract method divideData which defines + * how the data is to be divided into segments. These classes are extended by {@link ArrayInput} and + * {@link ArrayResult}.

*/ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** * Program entry point. + * * @param args command line args */ @@ -59,9 +66,9 @@ public static void main(String[] args) { ArrayTransposeMasterWorker mw = new ArrayTransposeMasterWorker(); int rows = 10; int columns = 20; - int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows,columns); + int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns); ArrayInput input = new ArrayInput(inputMatrix); - ArrayResult result = (ArrayResult) mw.getResult(input); + ArrayResult result = (ArrayResult) mw.getResult(input); if (result != null) { ArrayUtilityMethods.printMatrix(inputMatrix); ArrayUtilityMethods.printMatrix(result.data); diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java index df2d691b26eb..cd03a0a21895 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayInput.java @@ -27,8 +27,7 @@ import java.util.Arrays; /** - *Class ArrayInput extends abstract class {@link Input} and contains data - *of type int[][]. + * Class ArrayInput extends abstract class {@link Input} and contains data of type int[][]. */ public class ArrayInput extends Input { @@ -36,7 +35,7 @@ public class ArrayInput extends Input { public ArrayInput(int[][] data) { super(data); } - + static int[] makeDivisions(int[][] data, int num) { int initialDivision = data.length / num; //equally dividing int[] divisions = new int[num]; @@ -81,6 +80,6 @@ public ArrayList divideData(int num) { } } return result; - } - } + } + } } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java index dbe4f7477c12..a26472e80445 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayResult.java @@ -24,8 +24,7 @@ package com.iluwatar.masterworker; /** - *Class ArrayResult extends abstract class {@link Result} and contains data - *of type int[][]. + * Class ArrayResult extends abstract class {@link Result} and contains data of type int[][]. */ public class ArrayResult extends Result { diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java index 04db66492a13..525bed003e70 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/ArrayUtilityMethods.java @@ -23,23 +23,23 @@ package com.iluwatar.masterworker; +import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Random; - /** - *Class ArrayUtilityMethods has some utility methods for matrices and arrays. + * Class ArrayUtilityMethods has some utility methods for matrices and arrays. */ public class ArrayUtilityMethods { private static final Logger LOGGER = LoggerFactory.getLogger(ArrayUtilityMethods.class); - + private static final Random RANDOM = new Random(); + /** - * Method arraysSame compares 2 arrays @param a1 and @param a2 - * and @return whether their values are equal (boolean). + * Method arraysSame compares 2 arrays @param a1 and @param a2 and @return whether their values + * are equal (boolean). */ public static boolean arraysSame(int[] a1, int[] a2) { @@ -61,10 +61,10 @@ public static boolean arraysSame(int[] a1, int[] a2) { } /** - * Method matricesSame compares 2 matrices @param m1 and @param m2 - * and @return whether their values are equal (boolean). + * Method matricesSame compares 2 matrices @param m1 and @param m2 and @return whether their + * values are equal (boolean). */ - + public static boolean matricesSame(int[][] m1, int[][] m2) { if (m1.length != m2.length) { return false; @@ -81,12 +81,12 @@ public static boolean matricesSame(int[][] m1, int[][] m2) { return answer; } } - + /** - * Method createRandomIntMatrix creates a random matrix of size @param rows - * and @param columns @return it (int[][]). + * Method createRandomIntMatrix creates a random matrix of size @param rows and @param columns. + * + * @return it (int[][]). */ - public static int[][] createRandomIntMatrix(int rows, int columns) { int[][] matrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { @@ -97,11 +97,11 @@ public static int[][] createRandomIntMatrix(int rows, int columns) { } return matrix; } - + /** * Method printMatrix prints input matrix @param matrix. */ - + public static void printMatrix(int[][] matrix) { //prints out int[][] for (int i = 0; i < matrix.length; i++) { @@ -111,5 +111,5 @@ public static void printMatrix(int[][] matrix) { LOGGER.info(""); } } - + } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java index d0d0c2ddeac4..6a957ae804c3 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Input.java @@ -26,18 +26,19 @@ import java.util.ArrayList; /** - *The abstract Input class, having 1 public field which contains input data, - *and abstract method divideData. + * The abstract Input class, having 1 public field which contains input data, and abstract method + * divideData. + * * @param T will be type of data. */ public abstract class Input { - + public final T data; - + public Input(T data) { this.data = data; } - + public abstract ArrayList divideData(int num); } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java index 1bc729aa9228..79bc14604012 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/Result.java @@ -24,13 +24,13 @@ package com.iluwatar.masterworker; /** - *The abstract Result class, which contains 1 public field containing result - *data. + * The abstract Result class, which contains 1 public field containing result data. + * * @param T will be type of data. */ public abstract class Result { - + public final T data; public Result(T data) { diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java index 76e9ff35ab08..86c1a5700d95 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/ArrayTransposeMasterWorker.java @@ -27,8 +27,8 @@ import com.iluwatar.masterworker.system.systemmaster.Master; /** - *Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and - *specifically solves the problem of finding transpose of input array. + * Class ArrayTransposeMasterWorker extends abstract class {@link MasterWorker} and specifically + * solves the problem of finding transpose of input array. */ public class ArrayTransposeMasterWorker extends MasterWorker { diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java index 009faf106536..2b16cbf7628f 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/MasterWorker.java @@ -28,7 +28,7 @@ import com.iluwatar.masterworker.system.systemmaster.Master; /** - *The abstract MasterWorker class which contains reference to master. + * The abstract MasterWorker class which contains reference to master. */ public abstract class MasterWorker { diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java index 0a3ab79b7cc1..ffa64572ce64 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/ArrayTransposeMaster.java @@ -23,16 +23,15 @@ package com.iluwatar.masterworker.system.systemmaster; -import java.util.ArrayList; -import java.util.Enumeration; import com.iluwatar.masterworker.ArrayResult; import com.iluwatar.masterworker.system.systemworkers.ArrayTransposeWorker; import com.iluwatar.masterworker.system.systemworkers.Worker; +import java.util.ArrayList; +import java.util.Enumeration; /** - *Class ArrayTransposeMaster extends abstract class {@link Master} and contains - *definition of aggregateData, which will obtain final result from all - *data obtained and for setWorkers. + * Class ArrayTransposeMaster extends abstract class {@link Master} and contains definition of + * aggregateData, which will obtain final result from all data obtained and for setWorkers. */ public class ArrayTransposeMaster extends Master { @@ -43,26 +42,29 @@ public ArrayTransposeMaster(int numOfWorkers) { @Override ArrayList setWorkers(int num) { ArrayList ws = new ArrayList(num); - for (int i = 0; i < num ; i++) { + for (int i = 0; i < num; i++) { ws.add(new ArrayTransposeWorker(this, i + 1)); //i+1 will be id } return ws; } - + @Override ArrayResult aggregateData() { - //number of rows in final result is number of rows in any of obtained results obtained from workers - int rows = ((ArrayResult) this.getAllResultData().get(this.getAllResultData().keys().nextElement())).data.length; - int columns = 0; //number of columns is sum of number of columns in all results obtained from workers - for (Enumeration e = this.getAllResultData().keys(); e.hasMoreElements();) { + // number of rows in final result is number of rows in any of obtained results from workers + int rows = ((ArrayResult) this.getAllResultData() + .get(this.getAllResultData().keys().nextElement())).data.length; + int columns = + 0; //number of columns is sum of number of columns in all results obtained from workers + for (Enumeration e = this.getAllResultData().keys(); e.hasMoreElements(); ) { columns += ((ArrayResult) this.getAllResultData().get(e.nextElement())).data[0].length; } int[][] resultData = new int[rows][columns]; int columnsDone = 0; //columns aggregated so far for (int i = 0; i < this.getExpectedNumResults(); i++) { //result obtained from ith worker - int[][] work = ((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data; + int[][] work = + ((ArrayResult) this.getAllResultData().get(this.getWorkers().get(i).getWorkerId())).data; for (int m = 0; m < work.length; m++) { //m = row number, n = columns number for (int n = 0; n < work[0].length; n++) { @@ -73,5 +75,5 @@ ArrayResult aggregateData() { } return new ArrayResult(resultData); } - + } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java index 7e7d796eb718..2466df256f0c 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster/Master.java @@ -23,18 +23,17 @@ package com.iluwatar.masterworker.system.systemmaster; -import java.util.ArrayList; -import java.util.Hashtable; import com.iluwatar.masterworker.Input; import com.iluwatar.masterworker.Result; import com.iluwatar.masterworker.system.systemworkers.Worker; +import java.util.ArrayList; +import java.util.Hashtable; /** - *The abstract Master class which contains private fields numOfWorkers - *(number of workers), workers (arraylist of workers), expectedNumResults - *(number of divisions of input data, same as expected number of results), - *allResultData (hashtable of results obtained from workers, mapped by - *their ids) and finalResult (aggregated from allResultData). + * The abstract Master class which contains private fields numOfWorkers (number of workers), workers + * (arraylist of workers), expectedNumResults (number of divisions of input data, same as expected + * number of results), allResultData (hashtable of results obtained from workers, mapped by their + * ids) and finalResult (aggregated from allResultData). */ public abstract class Master { @@ -43,7 +42,7 @@ public abstract class Master { private int expectedNumResults; private Hashtable allResultData; private Result finalResult; - + Master(int numOfWorkers) { this.numOfWorkers = numOfWorkers; this.workers = setWorkers(numOfWorkers); @@ -51,46 +50,46 @@ public abstract class Master { this.allResultData = new Hashtable(numOfWorkers); this.finalResult = null; } - + public Result getFinalResult() { return this.finalResult; } - + Hashtable getAllResultData() { return this.allResultData; } - + int getExpectedNumResults() { return this.expectedNumResults; } - + ArrayList getWorkers() { return this.workers; } - + abstract ArrayList setWorkers(int num); - + public void doWork(Input input) { divideWork(input); } - + private void divideWork(Input input) { ArrayList dividedInput = input.divideData(numOfWorkers); if (dividedInput != null) { this.expectedNumResults = dividedInput.size(); - for (int i = 0; i < this.expectedNumResults; i++) { + for (int i = 0; i < this.expectedNumResults; i++) { //ith division given to ith worker in this.workers this.workers.get(i).setReceivedData(this, dividedInput.get(i)); this.workers.get(i).run(); } } } - + public void receiveData(Result data, Worker w) { //check if can receive..if yes: collectResult(data, w.getWorkerId()); } - + private void collectResult(Result data, int workerId) { this.allResultData.put(workerId, data); if (this.allResultData.size() == this.expectedNumResults) { @@ -98,6 +97,6 @@ private void collectResult(Result data, int workerId) { this.finalResult = aggregateData(); } } - + abstract Result aggregateData(); } diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java index 1d06fcc875da..37d8ba005699 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/ArrayTransposeWorker.java @@ -28,8 +28,8 @@ import com.iluwatar.masterworker.system.systemmaster.Master; /** - *Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method - *executeOperation(), to be performed on data received from master. + * Class ArrayTransposeWorker extends abstract class {@link Worker} and defines method + * executeOperation(), to be performed on data received from master. */ public class ArrayTransposeWorker extends Worker { @@ -41,12 +41,14 @@ public ArrayTransposeWorker(Master master, int id) { @Override ArrayResult executeOperation() { //number of rows in result matrix is equal to number of columns in input matrix and vice versa - int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length] - [((ArrayInput) this.getReceivedData()).data.length]; - for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) { - for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) { + ArrayInput arrayInput = (ArrayInput) this.getReceivedData(); + final int rows = arrayInput.data[0].length; + final int cols = arrayInput.data.length; + int[][] resultData = new int[rows][cols]; + for (int i = 0; i < cols; i++) { + for (int j = 0; j < rows; j++) { //flipping element positions along diagonal - resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j]; + resultData[j][i] = arrayInput.data[i][j]; } } return new ArrayResult(resultData); diff --git a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java index fff38e953216..bfe226ee0211 100644 --- a/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java +++ b/master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemworkers/Worker.java @@ -28,9 +28,8 @@ import com.iluwatar.masterworker.system.systemmaster.Master; /** - *The abstract Worker class which extends Thread class to enable parallel - *processing. Contains fields master(holding reference to master), workerId - *(unique id) and receivedData(from master). + * The abstract Worker class which extends Thread class to enable parallel processing. Contains + * fields master(holding reference to master), workerId (unique id) and receivedData(from master). */ public abstract class Worker extends Thread { @@ -61,7 +60,7 @@ public void setReceivedData(Master m, Input i) { private void sendToMaster(Result data) { this.master.receiveData(data, this); - } + } public void run() { //from Thread class Result work = executeOperation(); diff --git a/mediator/pom.xml b/mediator/pom.xml index 7fba84dd11ab..2c0bfd4135b6 100644 --- a/mediator/pom.xml +++ b/mediator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT mediator diff --git a/mediator/src/main/java/com/iluwatar/mediator/Action.java b/mediator/src/main/java/com/iluwatar/mediator/Action.java index dc89bcfdcd88..66e1f42c4672 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Action.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Action.java @@ -24,15 +24,15 @@ package com.iluwatar.mediator; /** - * * Action enumeration. - * */ public enum Action { - HUNT("hunted a rabbit", "arrives for dinner"), TALE("tells a tale", "comes to listen"), GOLD( - "found gold", "takes his share of the gold"), ENEMY("spotted enemies", "runs for cover"), NONE( - "", ""); + HUNT("hunted a rabbit", "arrives for dinner"), + TALE("tells a tale", "comes to listen"), + GOLD("found gold", "takes his share of the gold"), + ENEMY("spotted enemies", "runs for cover"), + NONE("", ""); private String title; private String description; diff --git a/mediator/src/main/java/com/iluwatar/mediator/App.java b/mediator/src/main/java/com/iluwatar/mediator/App.java index 9af600f7cc5e..9dbedb4abf69 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/App.java +++ b/mediator/src/main/java/com/iluwatar/mediator/App.java @@ -24,32 +24,31 @@ package com.iluwatar.mediator; /** - * * The Mediator pattern defines an object that encapsulates how a set of objects interact. This * pattern is considered to be a behavioral pattern due to the way it can alter the program's * running behavior. - *

- * Usually a program is made up of a large number of classes. So the logic and computation is + * + *

Usually a program is made up of a large number of classes. So the logic and computation is * distributed among these classes. However, as more classes are developed in a program, especially * during maintenance and/or refactoring, the problem of communication between these classes may * become more complex. This makes the program harder to read and maintain. Furthermore, it can * become difficult to change the program, since any change may affect code in several other * classes. - *

- * With the Mediator pattern, communication between objects is encapsulated with a mediator object. - * Objects no longer communicate directly with each other, but instead communicate through the - * mediator. This reduces the dependencies between communicating objects, thereby lowering the + * + *

With the Mediator pattern, communication between objects is encapsulated with a mediator + * object. Objects no longer communicate directly with each other, but instead communicate through + * the mediator. This reduces the dependencies between communicating objects, thereby lowering the * coupling. - *

- * In this example the mediator encapsulates how a set of objects ({@link PartyMember}) interact. - * Instead of referring to each other directly they use the mediator ({@link Party}) interface. - * + * + *

In this example the mediator encapsulates how a set of objects ({@link PartyMember}) + * interact. Instead of referring to each other directly they use the mediator ({@link Party}) + * interface. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java index 1ddec27ab3a9..1e1d53fc30dc 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hobbit.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Hobbit party member. - * */ public class Hobbit extends PartyMemberBase { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java index ed73c1684ccb..0711acf70fff 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Hunter.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Hunter.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Hunter party member. - * */ public class Hunter extends PartyMemberBase { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Party.java b/mediator/src/main/java/com/iluwatar/mediator/Party.java index c28b063f35b8..52d91e21d135 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Party.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Party.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Party interface. - * */ public interface Party { diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java index a2a755408620..6384a21872cf 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyImpl.java @@ -27,9 +27,7 @@ import java.util.List; /** - * * Party implementation. - * */ public class PartyImpl implements Party { diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java index a45b37b17cd3..c233a051af42 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMember.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Interface for party members interacting with {@link Party}. - * */ public interface PartyMember { diff --git a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java index 7ff3535e85d4..2d025db0c4ef 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java +++ b/mediator/src/main/java/com/iluwatar/mediator/PartyMemberBase.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Abstract base class for party members. - * */ public abstract class PartyMemberBase implements PartyMember { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java index 226bd8f04c4f..568510236d4c 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Rogue.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Rogue.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Rogue party member. - * */ public class Rogue extends PartyMemberBase { diff --git a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java index 33d7d6dce511..c138f0265115 100644 --- a/mediator/src/main/java/com/iluwatar/mediator/Wizard.java +++ b/mediator/src/main/java/com/iluwatar/mediator/Wizard.java @@ -24,9 +24,7 @@ package com.iluwatar.mediator; /** - * * Wizard party member. - * */ public class Wizard extends PartyMemberBase { diff --git a/memento/pom.xml b/memento/pom.xml index 260cb4c58016..07e4f0b839e5 100644 --- a/memento/pom.xml +++ b/memento/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT memento diff --git a/memento/src/main/java/com/iluwatar/memento/App.java b/memento/src/main/java/com/iluwatar/memento/App.java index fc6dffb06cb6..af57d8d4a2b7 100644 --- a/memento/src/main/java/com/iluwatar/memento/App.java +++ b/memento/src/main/java/com/iluwatar/memento/App.java @@ -23,36 +23,33 @@ package com.iluwatar.memento; +import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Stack; - /** - * * The Memento pattern is a software design pattern that provides the ability to restore an object * to its previous state (undo via rollback). - *

- * The Memento pattern is implemented with three objects: the originator, a caretaker and a memento. - * The originator is some object that has an internal state. The caretaker is going to do something - * to the originator, but wants to be able to undo the change. The caretaker first asks the - * originator for a memento object. Then it does whatever operation (or sequence of operations) it - * was going to do. To roll back to the state before the operations, it returns the memento object - * to the originator. The memento object itself is an opaque object (one which the caretaker cannot, - * or should not, change). When using this pattern, care should be taken if the originator may - * change other objects or resources - the memento pattern operates on a single object. - *

- * In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that + * + *

The Memento pattern is implemented with three objects: the originator, a caretaker and a + * memento. The originator is some object that has an internal state. The caretaker is going to do + * something to the originator, but wants to be able to undo the change. The caretaker first asks + * the originator for a memento object. Then it does whatever operation (or sequence of operations) + * it was going to do. To roll back to the state before the operations, it returns the memento + * object to the originator. The memento object itself is an opaque object (one which the caretaker + * cannot, or should not, change). When using this pattern, care should be taken if the originator + * may change other objects or resources - the memento pattern operates on a single object. + * + *

In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that * contains the state of the object. Later on the memento can be set back to the object restoring * the state. - * */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { Stack states = new Stack<>(); diff --git a/memento/src/main/java/com/iluwatar/memento/Star.java b/memento/src/main/java/com/iluwatar/memento/Star.java index 0e235752ec4e..ebeea28f291b 100644 --- a/memento/src/main/java/com/iluwatar/memento/Star.java +++ b/memento/src/main/java/com/iluwatar/memento/Star.java @@ -24,9 +24,7 @@ package com.iluwatar.memento; /** - * * Star uses "mementos" to store and restore state. - * */ public class Star { @@ -35,7 +33,7 @@ public class Star { private int massTons; /** - * Constructor + * Constructor. */ public Star(StarType startType, int startAge, int startMass) { this.type = startType; @@ -44,7 +42,7 @@ public Star(StarType startType, int startAge, int startMass) { } /** - * Makes time pass for the star + * Makes time pass for the star. */ public void timePasses() { ageYears *= 2; @@ -96,9 +94,7 @@ public String toString() { } /** - * - * StarMemento implementation - * + * StarMemento implementation. */ private static class StarMementoInternal implements StarMemento { diff --git a/memento/src/main/java/com/iluwatar/memento/StarMemento.java b/memento/src/main/java/com/iluwatar/memento/StarMemento.java index b94f5996a9db..7b7ccd3ec304 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarMemento.java +++ b/memento/src/main/java/com/iluwatar/memento/StarMemento.java @@ -24,9 +24,7 @@ package com.iluwatar.memento; /** - * * External interface to memento. - * */ public interface StarMemento { diff --git a/memento/src/main/java/com/iluwatar/memento/StarType.java b/memento/src/main/java/com/iluwatar/memento/StarType.java index 29da625799ce..507cd506b60a 100644 --- a/memento/src/main/java/com/iluwatar/memento/StarType.java +++ b/memento/src/main/java/com/iluwatar/memento/StarType.java @@ -24,9 +24,7 @@ package com.iluwatar.memento; /** - * - * StarType enumeration - * + * StarType enumeration. */ public enum StarType { diff --git a/model-view-controller/pom.xml b/model-view-controller/pom.xml index 035a6a27bb95..4759bf2d3158 100644 --- a/model-view-controller/pom.xml +++ b/model-view-controller/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT model-view-controller diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java index b4bc8f6ca4a6..4607f009df61 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/App.java @@ -24,27 +24,25 @@ package com.iluwatar.model.view.controller; /** - * * Model-View-Controller is a pattern for implementing user interfaces. It divides the application * into three interconnected parts namely the model, the view and the controller. - *

- * The central component of MVC, the model, captures the behavior of the application in terms of its - * problem domain, independent of the user interface. The model directly manages the data, logic and - * rules of the application. A view can be any output representation of information, such as a chart - * or a diagram The third part, the controller, accepts input and converts it to commands for the - * model or view. - *

- * In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and - * nourishment. {@link GiantView} can display the giant with its current status. - * {@link GiantController} receives input affecting the model and delegates redrawing the giant to - * the view. * + *

The central component of MVC, the model, captures the behavior of the application in terms of + * its problem domain, independent of the user interface. The model directly manages the data, logic + * and rules of the application. A view can be any output representation of information, such as a + * chart or a diagram The third part, the controller, accepts input and converts it to commands for + * the model or view. + * + *

In this example we have a giant ({@link GiantModel}) with statuses for health, fatigue and + * nourishment. {@link GiantView} can display the giant with its current status. {@link + * GiantController} receives input affecting the model and delegates redrawing the giant to the + * view. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java index 7f0fd293741c..b1663df1f3c1 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Fatigue.java @@ -24,9 +24,7 @@ package com.iluwatar.model.view.controller; /** - * - * Fatigue enumeration - * + * Fatigue enumeration. */ public enum Fatigue { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java index e420ec890870..e66608117479 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantController.java @@ -24,9 +24,7 @@ package com.iluwatar.model.view.controller; /** - * * GiantController can update the giant data and redraw it using the view. - * */ public class GiantController { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java index 4ae2c4c195ba..c80d0dba028d 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantModel.java @@ -24,9 +24,7 @@ package com.iluwatar.model.view.controller; /** - * - * GiantModel contains the giant data - * + * GiantModel contains the giant data. */ public class GiantModel { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java index 9590d609d61f..da14b7c08b60 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/GiantView.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * GiantView displays the giant - * + * GiantView displays the giant. */ public class GiantView { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java index c8b9374bf43b..30b3b2b90aeb 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Health.java @@ -24,9 +24,7 @@ package com.iluwatar.model.view.controller; /** - * - * Health enumeration - * + * Health enumeration. */ public enum Health { diff --git a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java index 9810b201565b..3ced564cc15a 100644 --- a/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java +++ b/model-view-controller/src/main/java/com/iluwatar/model/view/controller/Nourishment.java @@ -24,9 +24,7 @@ package com.iluwatar.model.view.controller; /** - * - * Nourishment enumeration - * + * Nourishment enumeration. */ public enum Nourishment { diff --git a/model-view-presenter/pom.xml b/model-view-presenter/pom.xml index 14de90aed9e8..21ba3f14c56d 100644 --- a/model-view-presenter/pom.xml +++ b/model-view-presenter/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT model-view-presenter model-view-presenter diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java index 9b6e6cde833f..43984e8475f8 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/App.java @@ -24,31 +24,29 @@ package com.iluwatar.model.view.presenter; /** - * - * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called - * "The separation of concerns" principle. This is accomplished by separating the application's - * logic (Model), GUIs (View), and finally the way that the user's actions update the application's - * logic (Presenter). - *

- * In the following example, The {@link FileLoader} class represents the app's logic, the - * {@link FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to - * respond to users' actions. - *

- * Finally, please notice the wiring between the Presenter and the View and between the Presenter - * and the Model. - * + * The Model-View-Presenter(MVP) architectural pattern, helps us achieve what is called "The + * separation of concerns" principle. This is accomplished by separating the application's logic + * (Model), GUIs (View), and finally the way that the user's actions update the application's logic + * (Presenter). + * + *

In the following example, The {@link FileLoader} class represents the app's logic, the {@link + * FileSelectorJFrame} is the GUI and the {@link FileSelectorPresenter} is responsible to respond to + * users' actions. + * + *

Finally, please notice the wiring between the Presenter and the View and between the + * Presenter and the Model. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { FileLoader loader = new FileLoader(); - FileSelectorJFrame jFrame = new FileSelectorJFrame(); - FileSelectorPresenter presenter = new FileSelectorPresenter(jFrame); + FileSelectorJFrame frame = new FileSelectorJFrame(); + FileSelectorPresenter presenter = new FileSelectorPresenter(frame); presenter.setLoader(loader); presenter.start(); } diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java index 980c0b56c2e9..9c01b2044f2d 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java @@ -27,23 +27,22 @@ import java.io.File; import java.io.FileReader; import java.io.Serializable; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Every instance of this class represents the Model component in the Model-View-Presenter * architectural pattern. - *

- * It is responsible for reading and loading the contents of a given file. + * + *

It is responsible for reading and loading the contents of a given file. */ public class FileLoader implements Serializable { /** - * Generated serial version UID + * Generated serial version UID. */ private static final long serialVersionUID = -4745803872902019069L; - + private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class); /** @@ -81,7 +80,7 @@ public String loadData() { /** * Sets the path of the file to be loaded, to the given value. - * + * * @param fileName The path of the file to be loaded. */ public void setFileName(String fileName) { @@ -89,6 +88,8 @@ public void setFileName(String fileName) { } /** + * Gets the path of the file to be loaded. + * * @return fileName The path of the file to be loaded. */ public String getFileName() { @@ -96,6 +97,8 @@ public String getFileName() { } /** + * Returns true if the given file exists. + * * @return True, if the file given exists, false otherwise. */ public boolean fileExists() { @@ -103,6 +106,8 @@ public boolean fileExists() { } /** + * Returns true if the given file is loaded. + * * @return True, if the file is loaded, false otherwise. */ public boolean isLoaded() { diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java index 3d9bc035a5ad..77523ccaa7be 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorJFrame.java @@ -26,7 +26,6 @@ import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; @@ -82,7 +81,7 @@ public class FileSelectorJFrame extends JFrame implements FileSelectorView, Acti private JPanel panel; /** - * The Presenter component that the frame will interact with + * The Presenter component that the frame will interact with. */ private FileSelectorPresenter presenter; diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java index a9cf1ba80a4c..35e1c0076712 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java @@ -28,13 +28,13 @@ /** * Every instance of this class represents the Presenter component in the Model-View-Presenter * architectural pattern. - *

- * It is responsible for reacting to the user's actions and update the View component. + * + *

It is responsible for reacting to the user's actions and update the View component. */ public class FileSelectorPresenter implements Serializable { /** - * Generated serial version UID + * Generated serial version UID. */ private static final long serialVersionUID = 1210314339075855074L; @@ -49,8 +49,8 @@ public class FileSelectorPresenter implements Serializable { private FileLoader loader; /** - * Constructor - * + * Constructor. + * * @param view The view component that the presenter will interact with. */ public FileSelectorPresenter(FileSelectorView view) { @@ -59,7 +59,7 @@ public FileSelectorPresenter(FileSelectorView view) { /** * Sets the {@link FileLoader} object, to the value given as parameter. - * + * * @param loader The new {@link FileLoader} object(the Model component). */ public void setLoader(FileLoader loader) { @@ -82,7 +82,7 @@ public void fileNameChanged() { } /** - * Ok button handler + * Ok button handler. */ public void confirmed() { if (loader.getFileName() == null || loader.getFileName().equals("")) { diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java index d034bcb04563..1d3aa07fbfcf 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorStub.java @@ -26,12 +26,12 @@ /** * Every instance of this class represents the Stub component in the Model-View-Presenter * architectural pattern. - *

- * The stub implements the View interface and it is useful when we want the test the reaction to + * + *

The stub implements the View interface and it is useful when we want the test the reaction to * user events, such as mouse clicks. - *

- * Since we can not test the GUI directly, the MVP pattern provides this functionality through the - * View's dummy implementation, the Stub. + * + *

Since we can not test the GUI directly, the MVP pattern provides this functionality through + * the View's dummy implementation, the Stub. */ public class FileSelectorStub implements FileSelectorView { @@ -61,7 +61,7 @@ public class FileSelectorStub implements FileSelectorView { private boolean dataDisplayed; /** - * Constructor + * Constructor. */ public FileSelectorStub() { this.opened = false; @@ -124,6 +124,8 @@ public int getMessagesSent() { } /** + * Returns true, if the data were displayed. + * * @return True if the data where displayed, false otherwise. */ public boolean dataDisplayed() { diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java index 3deec63d9692..e381784c53b4 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java @@ -42,44 +42,50 @@ public interface FileSelectorView extends Serializable { void close(); /** + * Returns true if view is opened. + * * @return True, if the view is opened, false otherwise. */ boolean isOpened(); /** * Sets the presenter component, to the one given as parameter. - * + * * @param presenter The new presenter component. */ void setPresenter(FileSelectorPresenter presenter); /** + * Gets presenter component. + * * @return The presenter Component. */ FileSelectorPresenter getPresenter(); /** * Sets the file's name, to the value given as parameter. - * + * * @param name The new name of the file. */ void setFileName(String name); /** + * Gets the name of file. + * * @return The name of the file. */ String getFileName(); /** * Displays a message to the users. - * + * * @param message The message to be displayed. */ void showMessage(String message); /** * Displays the data to the view. - * + * * @param data The data to be written. */ void displayData(String data); diff --git a/module/pom.xml b/module/pom.xml index 0a60960b53c6..d30353070a15 100644 --- a/module/pom.xml +++ b/module/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT module diff --git a/module/src/main/java/com/iluwatar/module/App.java b/module/src/main/java/com/iluwatar/module/App.java index af0432afb9af..1b6cbbd23aa2 100644 --- a/module/src/main/java/com/iluwatar/module/App.java +++ b/module/src/main/java/com/iluwatar/module/App.java @@ -31,10 +31,9 @@ * An object that applies this pattern can provide the equivalent of a namespace, providing the * initialization and finalization process of a static class or a class with static members with * cleaner, more concise syntax and semantics. - *

- * The below example demonstrates a use case for testing two different modules: File Logger and + * + *

The below example demonstrates a use case for testing two different modules: File Logger and * Console Logger - * */ public class App { @@ -42,10 +41,10 @@ public class App { public static ConsoleLoggerModule consoleLoggerModule; /** - * Following method performs the initialization - * + * Following method performs the initialization. + * * @throws FileNotFoundException if program is not able to find log files (output.txt and - * error.txt) + * error.txt) */ public static void prepare() throws FileNotFoundException { @@ -55,7 +54,7 @@ public static void prepare() throws FileNotFoundException { } /** - * Following method performs the finalization + * Following method performs the finalization. */ public static void unprepare() { @@ -65,8 +64,8 @@ public static void unprepare() { } /** - * Following method is main executor - * + * Following method is main executor. + * * @param args for providing default program arguments */ public static void execute(final String... args) { @@ -82,10 +81,10 @@ public static void execute(final String... args) { /** * Program entry point. - * + * * @param args command line args. * @throws FileNotFoundException if program is not able to find log files (output.txt and - * error.txt) + * error.txt) */ public static void main(final String... args) throws FileNotFoundException { prepare(); diff --git a/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java b/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java index 6e6d0539d0ba..7ca0d873d46d 100644 --- a/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java +++ b/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.java @@ -23,16 +23,15 @@ package com.iluwatar.module; +import java.io.PrintStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.PrintStream; - /** - * The ConsoleLoggerModule is responsible for showing logs on System Console - *

- * The below example demonstrates a Console logger module, which can print simple and error messages - * in two designated formats + * The ConsoleLoggerModule is responsible for showing logs on System Console. + * + *

The below example demonstrates a Console logger module, which can print simple and error + * messages in two designated formats */ public final class ConsoleLoggerModule { @@ -43,11 +42,12 @@ public final class ConsoleLoggerModule { public PrintStream output = null; public PrintStream error = null; - private ConsoleLoggerModule() {} + private ConsoleLoggerModule() { + } /** - * Static method to get single instance of class - * + * Static method to get single instance of class. + * * @return singleton instance of ConsoleLoggerModule */ public static ConsoleLoggerModule getSingleton() { @@ -60,7 +60,7 @@ public static ConsoleLoggerModule getSingleton() { } /** - * Following method performs the initialization + * Following method performs the initialization. */ public ConsoleLoggerModule prepare() { @@ -73,7 +73,7 @@ public ConsoleLoggerModule prepare() { } /** - * Following method performs the finalization + * Following method performs the finalization. */ public void unprepare() { @@ -93,8 +93,8 @@ public void unprepare() { } /** - * Used to print a message - * + * Used to print a message. + * * @param value will be printed on console */ public void printString(final String value) { @@ -102,8 +102,8 @@ public void printString(final String value) { } /** - * Used to print a error message - * + * Used to print a error message. + * * @param value will be printed on error console */ public void printErrorString(final String value) { diff --git a/module/src/main/java/com/iluwatar/module/FileLoggerModule.java b/module/src/main/java/com/iluwatar/module/FileLoggerModule.java index e461b31d7572..185bd0ae267d 100644 --- a/module/src/main/java/com/iluwatar/module/FileLoggerModule.java +++ b/module/src/main/java/com/iluwatar/module/FileLoggerModule.java @@ -23,18 +23,17 @@ package com.iluwatar.module; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * The FileLoggerModule is responsible for showing logs on File System - *

- * The below example demonstrates a File logger module, which can print simple and error messages in - * two designated files + * The FileLoggerModule is responsible for showing logs on File System. + * + *

The below example demonstrates a File logger module, which can print simple and error + * messages in two designated files */ public final class FileLoggerModule { @@ -48,11 +47,12 @@ public final class FileLoggerModule { public PrintStream output = null; public PrintStream error = null; - private FileLoggerModule() {} + private FileLoggerModule() { + } /** - * Static method to get single instance of class - * + * Static method to get single instance of class. + * * @return singleton instance of FileLoggerModule */ public static FileLoggerModule getSingleton() { @@ -65,10 +65,10 @@ public static FileLoggerModule getSingleton() { } /** - * Following method performs the initialization - * + * Following method performs the initialization. + * * @throws FileNotFoundException if program is not able to find log files (output.txt and - * error.txt) + * error.txt) */ public FileLoggerModule prepare() throws FileNotFoundException { @@ -81,7 +81,7 @@ public FileLoggerModule prepare() throws FileNotFoundException { } /** - * Following method performs the finalization + * Following method performs the finalization. */ public void unprepare() { @@ -101,8 +101,8 @@ public void unprepare() { } /** - * Used to print a message - * + * Used to print a message. + * * @param value will be printed in file */ public void printString(final String value) { @@ -110,8 +110,8 @@ public void printString(final String value) { } /** - * Used to print a error message - * + * Used to print a error message. + * * @param value will be printed on error file */ public void printErrorString(final String value) { diff --git a/monad/pom.xml b/monad/pom.xml index 67768a5d52b3..868cc871059b 100644 --- a/monad/pom.xml +++ b/monad/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT monad diff --git a/monad/src/main/java/com/iluwatar/monad/App.java b/monad/src/main/java/com/iluwatar/monad/App.java index 94e46548744c..ccb42edd027e 100644 --- a/monad/src/main/java/com/iluwatar/monad/App.java +++ b/monad/src/main/java/com/iluwatar/monad/App.java @@ -23,26 +23,27 @@ package com.iluwatar.monad; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * The Monad pattern defines a monad structure, that enables chaining operations - * in pipelines and processing data step by step. - * Formally, monad consists of a type constructor M and two operations: + * The Monad pattern defines a monad structure, that enables chaining operations in pipelines and + * processing data step by step. Formally, monad consists of a type constructor M and two + * operations: *
bind - that takes monadic object and a function from plain object to the * monadic value and returns monadic value. *
return - that takes plain type object and returns this object wrapped in a monadic value. - *

- * In the given example, the Monad pattern is represented as a {@link Validator} that takes an instance - * of a plain object with {@link Validator#of(Object)} - * and validates it {@link Validator#validate(Function, Predicate, String)} against given predicates. - *

As a validation result {@link Validator#get()} it either returns valid object {@link Validator#t} - * or throws a list of exceptions {@link Validator#exceptions} collected during validation. + * + *

In the given example, the Monad pattern is represented as a {@link Validator} that takes an + * instance of a plain object with {@link Validator#of(Object)} and validates it {@link + * Validator#validate(Function, Predicate, String)} against given predicates. + * + *

As a validation result {@link Validator#get()} it either returns valid object {@link + * Validator#t} or throws a list of exceptions {@link Validator#exceptions} collected during + * validation. */ public class App { @@ -58,6 +59,7 @@ public static void main(String[] args) { LOGGER.info(Validator.of(user).validate(User::getName, Objects::nonNull, "name is null") .validate(User::getName, name -> !name.isEmpty(), "name is empty") .validate(User::getEmail, email -> !email.contains("@"), "email doesn't containt '@'") - .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get().toString()); + .validate(User::getAge, age -> age > 20 && age < 30, "age isn't between...").get() + .toString()); } } diff --git a/monad/src/main/java/com/iluwatar/monad/Sex.java b/monad/src/main/java/com/iluwatar/monad/Sex.java index 960711656021..cc772c340009 100644 --- a/monad/src/main/java/com/iluwatar/monad/Sex.java +++ b/monad/src/main/java/com/iluwatar/monad/Sex.java @@ -24,7 +24,7 @@ package com.iluwatar.monad; /** - * Enumeration of Types of Sex + * Enumeration of Types of Sex. */ public enum Sex { MALE, FEMALE diff --git a/monad/src/main/java/com/iluwatar/monad/User.java b/monad/src/main/java/com/iluwatar/monad/User.java index 9ecaa527539c..77766d1aa25f 100644 --- a/monad/src/main/java/com/iluwatar/monad/User.java +++ b/monad/src/main/java/com/iluwatar/monad/User.java @@ -24,7 +24,7 @@ package com.iluwatar.monad; /** - * User Definition + * User Definition. */ public class User { @@ -34,6 +34,8 @@ public class User { private String email; /** + * Constructor. + * * @param name - name * @param age - age * @param sex - sex diff --git a/monad/src/main/java/com/iluwatar/monad/Validator.java b/monad/src/main/java/com/iluwatar/monad/Validator.java index b5618f91c390..2d1f1bdab177 100644 --- a/monad/src/main/java/com/iluwatar/monad/Validator.java +++ b/monad/src/main/java/com/iluwatar/monad/Validator.java @@ -30,18 +30,18 @@ import java.util.function.Predicate; /** - * Class representing Monad design pattern. Monad is a way of chaining operations on the - * given object together step by step. In Validator each step results in either success or - * failure indicator, giving a way of receiving each of them easily and finally getting - * validated object or list of exceptions. + * Class representing Monad design pattern. Monad is a way of chaining operations on the given + * object together step by step. In Validator each step results in either success or failure + * indicator, giving a way of receiving each of them easily and finally getting validated object or + * list of exceptions. * * @param Placeholder for an object. */ public class Validator { /** - * Object that is validated + * Object that is validated. */ - private final T t; + private final T obj; /** * List of exception thrown during validation. @@ -50,14 +50,15 @@ public class Validator { /** * Creates a monadic value of given object. - * @param t object to be validated + * + * @param obj object to be validated */ - private Validator(T t) { - this.t = t; + private Validator(T obj) { + this.obj = obj; } /** - * Creates validator against given object + * Creates validator against given object. * * @param t object to be validated * @param object's type @@ -68,25 +69,27 @@ public static Validator of(T t) { } /** - * @param validation one argument boolean-valued function that - * represents one step of validation. Adds exception to main validation exception - * list when single step validation ends with failure. + * Checks if the validation is successful. + * + * @param validation one argument boolean-valued function that represents one step of validation. + * Adds exception to main validation exception list when single step validation + * ends with failure. * @param message error message when object is invalid * @return this */ public Validator validate(Predicate validation, String message) { - if (!validation.test(t)) { + if (!validation.test(obj)) { exceptions.add(new IllegalStateException(message)); } return this; } /** - * Extension for the {@link Validator#validate(Function, Predicate, String)} method, - * dedicated for objects, that need to be projected before requested validation. + * Extension for the {@link Validator#validate(Function, Predicate, String)} method, dedicated for + * objects, that need to be projected before requested validation. * - * @param projection function that gets an objects, and returns projection representing - * element to be validated. + * @param projection function that gets an objects, and returns projection representing element to + * be validated. * @param validation see {@link Validator#validate(Function, Predicate, String)} * @param message see {@link Validator#validate(Function, Predicate, String)} * @param see {@link Validator#validate(Function, Predicate, String)} @@ -105,7 +108,7 @@ public Validator validate(Function projection, Predicate validat */ public T get() throws IllegalStateException { if (exceptions.isEmpty()) { - return t; + return obj; } IllegalStateException e = new IllegalStateException(); exceptions.forEach(e::addSuppressed); diff --git a/monostate/pom.xml b/monostate/pom.xml index b39ef2d95b06..0e51fc70084a 100644 --- a/monostate/pom.xml +++ b/monostate/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT monostate diff --git a/monostate/src/main/java/com/iluwatar/monostate/App.java b/monostate/src/main/java/com/iluwatar/monostate/App.java index 4b6f8b14b64d..64cb384612c1 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/App.java +++ b/monostate/src/main/java/com/iluwatar/monostate/App.java @@ -24,28 +24,22 @@ package com.iluwatar.monostate; - /** - * * The MonoState pattern ensures that all instances of the class will have the same state. This can * be used a direct replacement of the Singleton pattern. - * - *

- * In the following example, The {@link LoadBalancer} class represents the app's logic. It contains - * a series of Servers, which can handle requests of type {@link Request}. Two instances of + * + *

In the following example, The {@link LoadBalancer} class represents the app's logic. It + * contains a series of Servers, which can handle requests of type {@link Request}. Two instances of * LoadBalacer are created. When a request is made to a server via the first LoadBalancer the state * change in the first load balancer affects the second. So if the first LoadBalancer selects the * Server 1, the second LoadBalancer on a new request will select the Second server. If a third * LoadBalancer is created and a new request is made to it, then it will select the third server as * the second load balancer has already selected the second server. - *

- * . - * */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java index ae590be5ee5d..8546ae1777bf 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java +++ b/monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java @@ -31,7 +31,6 @@ * receiving a new Request, it delegates the call to the servers in a Round Robin Fashion. Since all * instances of the class share the same state, all instances will delegate to the same server on * receiving a new Request. - * */ public class LoadBalancer { @@ -40,13 +39,13 @@ public class LoadBalancer { static { int id = 0; - for (int port : new int[] {8080, 8081, 8082, 8083, 8084}) { + for (int port : new int[]{8080, 8081, 8082, 8083, 8084}) { SERVERS.add(new Server("localhost", port, ++id)); } } /** - * Add new server + * Add new server. */ public final void addServer(Server server) { synchronized (SERVERS) { @@ -64,7 +63,7 @@ public int getLastServedId() { } /** - * Handle request + * Handle request. */ public synchronized void serverRequest(Request request) { if (lastServedId >= SERVERS.size()) { @@ -73,5 +72,5 @@ public synchronized void serverRequest(Request request) { Server server = SERVERS.get(lastServedId++); server.serve(request); } - + } diff --git a/monostate/src/main/java/com/iluwatar/monostate/Request.java b/monostate/src/main/java/com/iluwatar/monostate/Request.java index 5a7429998ac1..d7e4fcf8f9a5 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Request.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Request.java @@ -24,9 +24,7 @@ package com.iluwatar.monostate; /** - * * The Request class. A {@link Server} can handle an instance of a Request. - * */ public class Request { diff --git a/monostate/src/main/java/com/iluwatar/monostate/Server.java b/monostate/src/main/java/com/iluwatar/monostate/Server.java index fa809864cb83..cd08b2b29613 100644 --- a/monostate/src/main/java/com/iluwatar/monostate/Server.java +++ b/monostate/src/main/java/com/iluwatar/monostate/Server.java @@ -27,10 +27,8 @@ import org.slf4j.LoggerFactory; /** - * * The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers * in a simplistic Round Robin fashion. - * */ public class Server { @@ -41,7 +39,7 @@ public class Server { public final int id; /** - * Constructor + * Constructor. */ public Server(String host, int port, int id) { this.host = host; @@ -59,6 +57,6 @@ public int getPort() { public void serve(Request request) { LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}", - id, host, port, request.value); + id, host, port, request.value); } } diff --git a/multiton/pom.xml b/multiton/pom.xml index cd827aa6de27..39deb9e4dcbe 100644 --- a/multiton/pom.xml +++ b/multiton/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT multiton diff --git a/multiton/src/main/java/com/iluwatar/multiton/App.java b/multiton/src/main/java/com/iluwatar/multiton/App.java index 8fb226625eae..eb3e0313fe1f 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/App.java +++ b/multiton/src/main/java/com/iluwatar/multiton/App.java @@ -27,26 +27,24 @@ import org.slf4j.LoggerFactory; /** - * * Whereas Singleton design pattern introduces single globally accessible object the Multiton * pattern defines many globally accessible objects. The client asks for the correct instance from * the Multiton by passing an enumeration as parameter. - *

- * There is more than one way to implement the multiton design pattern. In the first example - * {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using {@link NazgulName}. - * The {@link Nazgul}s are statically initialized and stored in concurrent hash map. - *

- * In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable because - * of the way java supports enums. * + *

There is more than one way to implement the multiton design pattern. In the first example + * {@link Nazgul} is the Multiton and we can ask single {@link Nazgul} from it using {@link + * NazgulName}. The {@link Nazgul}s are statically initialized and stored in concurrent hash map. + * + *

In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable + * because of the way java supports enums. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { @@ -60,7 +58,7 @@ public static void main(String[] args) { LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL)); LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN)); LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA)); - + // enum multiton LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL); LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR); diff --git a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java index 52a25e00d665..f55f85aca722 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java +++ b/multiton/src/main/java/com/iluwatar/multiton/Nazgul.java @@ -27,9 +27,7 @@ import java.util.concurrent.ConcurrentHashMap; /** - * * Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method. - * */ public final class Nazgul { diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java index f119ee68fb59..5b5c48d66ff1 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java +++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulEnum.java @@ -24,11 +24,10 @@ package com.iluwatar.multiton; /** - * enum based multiton implementation - * + * enum based multiton implementation. */ public enum NazgulEnum { - + KHAMUL, MURAZOR, DWAR, JI_INDUR, AKHORAHIL, HOARMURATH, ADUNAPHEL, REN, UVATHA; } diff --git a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java index 5fe2a5a0f427..c7865dceb0a9 100644 --- a/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java +++ b/multiton/src/main/java/com/iluwatar/multiton/NazgulName.java @@ -24,9 +24,7 @@ package com.iluwatar.multiton; /** - * * Each Nazgul has different {@link NazgulName}. - * */ public enum NazgulName { diff --git a/mute-idiom/pom.xml b/mute-idiom/pom.xml index aeb18dc5ce6e..91f5063a7a0e 100644 --- a/mute-idiom/pom.xml +++ b/mute-idiom/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT mute-idiom diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/App.java b/mute-idiom/src/main/java/com/iluwatar/mute/App.java index 28649e24990a..d4f140bf089e 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/App.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/App.java @@ -23,19 +23,17 @@ package com.iluwatar.mute; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.sql.SQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Mute pattern is utilized when we need to suppress an exception due to an API flaw or in - * situation when all we can do to handle the exception is to log it. - * This pattern should not be used everywhere. It is very important to logically handle the - * exceptions in a system, but some situations like the ones described above require this pattern, - * so that we don't need to repeat + * Mute pattern is utilized when we need to suppress an exception due to an API flaw or in situation + * when all we can do to handle the exception is to log it. This pattern should not be used + * everywhere. It is very important to logically handle the exceptions in a system, but some + * situations like the ones described above require this pattern, so that we don't need to repeat *

  * 
  *   try {
@@ -45,7 +43,6 @@
  *   }
  * 
  * 
every time we need to ignore an exception. - * */ public class App { @@ -53,7 +50,7 @@ public class App { /** * Program entry point. - * + * * @param args command line args. * @throws Exception if any exception occurs */ @@ -65,7 +62,7 @@ public static void main(String[] args) throws Exception { } /* - * Typically used when the API declares some exception but cannot do so. Usually a + * Typically used when the API declares some exception but cannot do so. Usually a * signature mistake.In this example out is not supposed to throw exception as it is a * ByteArrayOutputStream. So we utilize mute, which will throw AssertionError if unexpected * exception occurs. @@ -98,7 +95,7 @@ private static void utilizeResource(Resource resource) throws SQLException { private static Resource acquireResource() throws SQLException { return new Resource() { - + @Override public void close() throws IOException { throw new IOException("Error in closing resource: " + this); diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java index d5fdaaec2b34..f15153d0083d 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java @@ -25,12 +25,12 @@ /** * A runnable which may throw exception on execution. - * */ @FunctionalInterface public interface CheckedRunnable { /** * Same as {@link Runnable#run()} with a possibility of exception in execution. + * * @throws Exception if any exception occurs. */ void run() throws Exception; diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java index 87a1f651e77f..30e1698d5d1b 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Mute.java @@ -30,17 +30,18 @@ * A utility class that allows you to utilize mute idiom. */ public final class Mute { - + // The constructor is never meant to be called. - private Mute() {} + private Mute() { + } /** - * Executes the runnable and throws the exception occurred within a {@link AssertionError}. - * This method should be utilized to mute the operations that are guaranteed not to throw an exception. - * For instance {@link ByteArrayOutputStream#write(byte[])} declares in it's signature that it can throw - * an {@link IOException}, but in reality it cannot. This is because the bulk write method is not overridden - * in {@link ByteArrayOutputStream}. - * + * Executes the runnable and throws the exception occurred within a {@link + * AssertionError}. This method should be utilized to mute the operations that are guaranteed not + * to throw an exception. For instance {@link ByteArrayOutputStream#write(byte[])} declares in + * it's signature that it can throw an {@link IOException}, but in reality it cannot. This is + * because the bulk write method is not overridden in {@link ByteArrayOutputStream}. + * * @param runnable a runnable that should never throw an exception on execution. */ public static void mute(CheckedRunnable runnable) { @@ -52,11 +53,11 @@ public static void mute(CheckedRunnable runnable) { } /** - * Executes the runnable and logs the exception occurred on {@link System#err}. - * This method should be utilized to mute the operations about which most you can do is log. - * For instance while closing a connection to database, or cleaning up a resource, - * all you can do is log the exception occurred. - * + * Executes the runnable and logs the exception occurred on {@link System#err}. This + * method should be utilized to mute the operations about which most you can do is log. For + * instance while closing a connection to database, or cleaning up a resource, all you can do is + * log the exception occurred. + * * @param runnable a runnable that may throw an exception on execution. */ public static void loggedMute(CheckedRunnable runnable) { diff --git a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java index a10fe4617605..e56025ce4ea8 100644 --- a/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java +++ b/mute-idiom/src/main/java/com/iluwatar/mute/Resource.java @@ -26,9 +26,8 @@ import java.io.Closeable; /** - * Represents any resource that the application might acquire and that must be closed - * after it is utilized. Example of such resources can be a database connection, open - * files, sockets. + * Represents any resource that the application might acquire and that must be closed after it is + * utilized. Example of such resources can be a database connection, open files, sockets. */ public interface Resource extends Closeable { diff --git a/mutex/pom.xml b/mutex/pom.xml index 05f9295eead8..c1cad3d8aae4 100644 --- a/mutex/pom.xml +++ b/mutex/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT mutex diff --git a/mutex/src/main/java/com/iluwatar/mutex/App.java b/mutex/src/main/java/com/iluwatar/mutex/App.java index 827307d0f884..e4a952ef9f46 100644 --- a/mutex/src/main/java/com/iluwatar/mutex/App.java +++ b/mutex/src/main/java/com/iluwatar/mutex/App.java @@ -25,19 +25,17 @@ /** * A Mutex prevents multiple threads from accessing a resource simultaneously. - *

- * In this example we have two thieves who are taking beans from a jar. - * Only one thief can take a bean at a time. This is ensured by a Mutex lock - * which must be acquired in order to access the jar. Each thief attempts to - * acquire the lock, take a bean and then release the lock. If the lock has - * already been acquired, the thief will be prevented from continuing (blocked) - * until the lock has been released. The thieves stop taking beans once there - * are no beans left to take. + * + *

In this example we have two thieves who are taking beans from a jar. Only one thief can take + * a bean at a time. This is ensured by a Mutex lock which must be acquired in order to access the + * jar. Each thief attempts to acquire the lock, take a bean and then release the lock. If the lock + * has already been acquired, the thief will be prevented from continuing (blocked) until the lock + * has been released. The thieves stop taking beans once there are no beans left to take. */ public class App { /** - * main method + * main method. */ public static void main(String[] args) { Mutex mutex = new Mutex(); diff --git a/mutex/src/main/java/com/iluwatar/mutex/Jar.java b/mutex/src/main/java/com/iluwatar/mutex/Jar.java index 427907f31d90..f68b266add5f 100644 --- a/mutex/src/main/java/com/iluwatar/mutex/Jar.java +++ b/mutex/src/main/java/com/iluwatar/mutex/Jar.java @@ -24,9 +24,8 @@ package com.iluwatar.mutex; /** - * A Jar has a resource of beans which can only be accessed by a single Thief - * (thread) at any one time. A Mutex lock is used to prevent more than one Thief - * taking a bean simultaneously. + * A Jar has a resource of beans which can only be accessed by a single Thief (thread) at any one + * time. A Mutex lock is used to prevent more than one Thief taking a bean simultaneously. */ public class Jar { diff --git a/mutex/src/main/java/com/iluwatar/mutex/Mutex.java b/mutex/src/main/java/com/iluwatar/mutex/Mutex.java index a2ef71f11d1f..6c62cc8ea930 100644 --- a/mutex/src/main/java/com/iluwatar/mutex/Mutex.java +++ b/mutex/src/main/java/com/iluwatar/mutex/Mutex.java @@ -34,16 +34,15 @@ public class Mutex implements Lock { private Object owner; /** - * Returns the current owner of the Mutex, or null if available + * Returns the current owner of the Mutex, or null if available. */ public Object getOwner() { return owner; } - + /** - * Method called by a thread to acquire the lock. If the lock has already - * been acquired this will wait until the lock has been released to - * re-attempt the acquire. + * Method called by a thread to acquire the lock. If the lock has already been acquired this will + * wait until the lock has been released to re-attempt the acquire. */ @Override public synchronized void acquire() throws InterruptedException { diff --git a/mutex/src/main/java/com/iluwatar/mutex/Thief.java b/mutex/src/main/java/com/iluwatar/mutex/Thief.java index f88e46d96fab..29caba540ad1 100644 --- a/mutex/src/main/java/com/iluwatar/mutex/Thief.java +++ b/mutex/src/main/java/com/iluwatar/mutex/Thief.java @@ -27,20 +27,20 @@ import org.slf4j.LoggerFactory; /** - * Thief is a class which continually tries to acquire a jar and take a bean - * from it. When the jar is empty the thief stops. + * Thief is a class which continually tries to acquire a jar and take a bean from it. When the jar + * is empty the thief stops. */ public class Thief extends Thread { private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class); /** - * The name of the thief. + * The name of the thief. */ private final String name; - + /** - * The jar + * The jar. */ private final Jar jar; @@ -50,8 +50,7 @@ public Thief(String name, Jar jar) { } /** - * In the run method the thief repeatedly tries to take a bean until none - * are left. + * In the run method the thief repeatedly tries to take a bean until none are left. */ @Override public void run() { diff --git a/naked-objects/dom/pom.xml b/naked-objects/dom/pom.xml index 2709edda03f4..dffc1650caad 100644 --- a/naked-objects/dom/pom.xml +++ b/naked-objects/dom/pom.xml @@ -30,7 +30,7 @@ com.iluwatar naked-objects - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT naked-objects-dom diff --git a/naked-objects/fixture/pom.xml b/naked-objects/fixture/pom.xml index 9de092976117..3457ac0a42ab 100644 --- a/naked-objects/fixture/pom.xml +++ b/naked-objects/fixture/pom.xml @@ -30,7 +30,7 @@ com.iluwatar naked-objects - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT naked-objects-fixture diff --git a/naked-objects/integtests/pom.xml b/naked-objects/integtests/pom.xml index 62d25df032c9..f46541f48fb4 100644 --- a/naked-objects/integtests/pom.xml +++ b/naked-objects/integtests/pom.xml @@ -30,7 +30,7 @@ com.iluwatar naked-objects - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT naked-objects-integtests diff --git a/naked-objects/pom.xml b/naked-objects/pom.xml index b035c3894058..0ca5a3ef3cb4 100644 --- a/naked-objects/pom.xml +++ b/naked-objects/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT naked-objects pom @@ -333,17 +333,17 @@ ${project.groupId} naked-objects-dom - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT ${project.groupId} naked-objects-fixture - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT ${project.groupId} naked-objects-webapp - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/naked-objects/webapp/pom.xml b/naked-objects/webapp/pom.xml index e0697b855b31..bdf638cbaa3a 100644 --- a/naked-objects/webapp/pom.xml +++ b/naked-objects/webapp/pom.xml @@ -30,7 +30,7 @@ com.iluwatar naked-objects - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT naked-objects-webapp diff --git a/null-object/pom.xml b/null-object/pom.xml index 7111c8ff9822..d80b97d95734 100644 --- a/null-object/pom.xml +++ b/null-object/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT null-object diff --git a/object-mother/pom.xml b/object-mother/pom.xml index e59607414c6e..5ac3ce410b6c 100644 --- a/object-mother/pom.xml +++ b/object-mother/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT object-mother diff --git a/object-pool/pom.xml b/object-pool/pom.xml index efbb7ee4047c..fdd247476d12 100644 --- a/object-pool/pom.xml +++ b/object-pool/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT object-pool diff --git a/observer/pom.xml b/observer/pom.xml index 9a538aa294d9..fc8a53eae564 100644 --- a/observer/pom.xml +++ b/observer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT observer diff --git a/page-object/pom.xml b/page-object/pom.xml index 7a3db030ee16..99c67dbc5f38 100644 --- a/page-object/pom.xml +++ b/page-object/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT page-object pom diff --git a/page-object/sample-application/pom.xml b/page-object/sample-application/pom.xml index c21e52e9901c..5ded184cc74f 100644 --- a/page-object/sample-application/pom.xml +++ b/page-object/sample-application/pom.xml @@ -29,7 +29,7 @@ page-object com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT sample-application diff --git a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java index aae08c15f80e..e3a86599c3fb 100644 --- a/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/sample-application/src/main/java/com/iluwatar/pageobject/App.java @@ -26,63 +26,60 @@ import java.awt.Desktop; import java.io.File; import java.io.IOException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Page Object pattern wraps an UI component with an application specific API allowing you to - * manipulate the UI elements without having to dig around with the underlying UI technology used. This is - * especially useful for testing as it means your tests will be less brittle. Your tests can concentrate on - * the actual test cases where as the manipulation of the UI can be left to the internals of the page object - * itself. + * manipulate the UI elements without having to dig around with the underlying UI technology used. + * This is especially useful for testing as it means your tests will be less brittle. Your tests can + * concentrate on the actual test cases where as the manipulation of the UI can be left to the + * internals of the page object itself. * - *

- * Due to this reason, it has become very popular within the test automation community. - * In particular, it is very common in that the page object is used to represent the html pages of a - * web application that is under test. This web application is referred to as AUT (Application Under Test). - * A web browser automation tool/framework like Selenium for instance, is then used to drive the automating - * of the browser navigation and user actions journeys through this web application. Your test class would - * therefore only be responsible for particular test cases and page object would be used by the test class - * for UI manipulation required for the tests. + *

Due to this reason, it has become very popular within the test automation community. In + * particular, it is very common in that the page object is used to represent the html pages of a + * web application that is under test. This web application is referred to as AUT (Application Under + * Test). A web browser automation tool/framework like Selenium for instance, is then used to drive + * the automating of the browser navigation and user actions journeys through this web application. + * Your test class would therefore only be responsible for particular test cases and page object + * would be used by the test class for UI manipulation required for the tests. * - *

- * In this implementation rather than using Selenium, the HtmlUnit library is used as a replacement to - * represent the specific html elements and to drive the browser. The purpose of this example is just to - * provide a simple version that showcase the intentions of this pattern and how this pattern is used - * in order to understand it. + *

In this implementation rather than using Selenium, the HtmlUnit library is used as a + * replacement to represent the specific html elements and to drive the browser. The purpose of this + * example is just to provide a simple version that showcase the intentions of this pattern and how + * this pattern is used in order to understand it. */ public final class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private App() { } /** * Application entry point * - *

- * The application under development is a web application. Normally you would probably have a - * backend that is probably implemented in an object-oriented language (e.g. Java) that serves - * the frontend which comprises of a series of HTML, CSS, JS etc... + *

The application under development is a web application. Normally you would probably have a + * backend that is probably implemented in an object-oriented language (e.g. Java) that serves the + * frontend which comprises of a series of HTML, CSS, JS etc... * - *

- * For illustrations purposes only, a very simple static html app is used here. This main method - * just fires up this simple web app in a default browser. + *

For illustrations purposes only, a very simple static html app is used here. This main + * method just fires up this simple web app in a default browser. * * @param args arguments */ public static void main(String[] args) { try { - File applicationFile = new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); + File applicationFile = + new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); // should work for unix like OS (mac, unix etc...) if (Desktop.isDesktopSupported()) { Desktop.getDesktop().open(applicationFile); } else { - // java Desktop not supported - above unlikely to work for Windows so try following instead... + // java Desktop not supported - above unlikely to work for Windows so try instead... Runtime.getRuntime().exec("cmd.exe start " + applicationFile); } diff --git a/page-object/src/main/java/com/iluwatar/pageobject/App.java b/page-object/src/main/java/com/iluwatar/pageobject/App.java index c76867e89899..ee9f58504a0b 100644 --- a/page-object/src/main/java/com/iluwatar/pageobject/App.java +++ b/page-object/src/main/java/com/iluwatar/pageobject/App.java @@ -29,25 +29,23 @@ /** * Page Object pattern wraps an UI component with an application specific API allowing you to - * manipulate the UI elements without having to dig around with the underlying UI technology used. This is - * especially useful for testing as it means your tests will be less brittle. Your tests can concentrate on - * the actual test cases where as the manipulation of the UI can be left to the internals of the page object - * itself. + * manipulate the UI elements without having to dig around with the underlying UI technology used. + * This is especially useful for testing as it means your tests will be less brittle. Your tests can + * concentrate on the actual test cases where as the manipulation of the UI can be left to the + * internals of the page object itself. * - *

- * Due to this reason, it has become very popular within the test automation community. - * In particular, it is very common in that the page object is used to represent the html pages of a - * web application that is under test. This web application is referred to as AUT (Application Under Test). - * A web browser automation tool/framework like Selenium for instance, is then used to drive the automating - * of the browser navigation and user actions journeys through this web application. Your test class would - * therefore only be responsible for particular test cases and page object would be used by the test class - * for UI manipulation required for the tests. + *

Due to this reason, it has become very popular within the test automation community. In + * particular, it is very common in that the page object is used to represent the html pages of a + * web application that is under test. This web application is referred to as AUT (Application Under + * Test). A web browser automation tool/framework like Selenium for instance, is then used to drive + * the automating of the browser navigation and user actions journeys through this web application. + * Your test class would therefore only be responsible for particular test cases and page object + * would be used by the test class for UI manipulation required for the tests. * - *

- * In this implementation rather than using Selenium, the HtmlUnit library is used as a replacement to - * represent the specific html elements and to drive the browser. The purpose of this example is just to - * provide a simple version that showcase the intentions of this pattern and how this pattern is used - * in order to understand it. + *

In this implementation rather than using Selenium, the HtmlUnit library is used as a + * replacement to represent the specific html elements and to drive the browser. The purpose of this + * example is just to provide a simple version that showcase the intentions of this pattern and how + * this pattern is used in order to understand it. */ public final class App { @@ -57,28 +55,28 @@ private App() { /** * Application entry point * - *

- * The application under development is a web application. Normally you would probably have a - * backend that is probably implemented in an object-oriented language (e.g. Java) that serves - * the frontend which comprises of a series of HTML, CSS, JS etc... + *

The application under development is a web application. Normally you would probably have a + * backend that is probably implemented in an object-oriented language (e.g. Java) that serves the + * frontend which comprises of a series of HTML, CSS, JS etc... * - *

- * For illustrations purposes only, a very simple static html app is used here. This main method - * just fires up this simple web app in a default browser. + *

For illustrations purposes only, a very simple static html app is used here. This main + * method just fires up this simple web app in a default browser. * * @param args arguments */ public static void main(String[] args) { try { - File applicationFile = new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); + File applicationFile = + new File(App.class.getClassLoader().getResource("sample-ui/login.html").getPath()); - // should work for unix like OS (mac, unix etc...) + // Should work for unix like OS (mac, unix etc...) if (Desktop.isDesktopSupported()) { Desktop.getDesktop().open(applicationFile); } else { - // java Desktop not supported - above unlikely to work for Windows so try following instead... + // Java Desktop not supported - above unlikely to work for Windows so try the + // following instead... Runtime.getRuntime().exec("cmd.exe start " + applicationFile); } diff --git a/page-object/test-automation/pom.xml b/page-object/test-automation/pom.xml index 5b275084c4cf..68025f4b82dd 100644 --- a/page-object/test-automation/pom.xml +++ b/page-object/test-automation/pom.xml @@ -29,7 +29,7 @@ page-object com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT test-automation diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java index feab7838c7bd..2851d24d54c1 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumListPage.java @@ -26,10 +26,8 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; - import java.io.IOException; import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,7 +44,7 @@ public class AlbumListPage extends Page { /** - * Constructor + * Constructor. */ public AlbumListPage(WebClient webClient) { super(webClient); @@ -54,7 +52,7 @@ public AlbumListPage(WebClient webClient) { /** - * Navigates to the Album List Page + * Navigates to the Album List Page. * * @return {@link AlbumListPage} */ @@ -76,7 +74,7 @@ public boolean isAt() { } /** - * Selects an album by the given album title + * Selects an album by the given album title. * * @param albumTitle the title of the album to click * @return the album page diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java index cf8c50dd74a1..953a47ba2e39 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/AlbumPage.java @@ -23,11 +23,6 @@ package com.iluwatar.pageobject; -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlNumberInput; import com.gargoylesoftware.htmlunit.html.HtmlOption; @@ -35,6 +30,9 @@ import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; +import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Page Object encapsulating the Album Page (album-page.html) @@ -49,7 +47,7 @@ public class AlbumPage extends Page { /** - * Constructor + * Constructor. */ public AlbumPage(WebClient webClient) { super(webClient); @@ -57,7 +55,7 @@ public AlbumPage(WebClient webClient) { /** - * Navigates to the album page + * Navigates to the album page. * * @return {@link AlbumPage} */ @@ -81,7 +79,7 @@ public boolean isAt() { /** - * Sets the album title input text field + * Sets the album title input text field. * * @param albumTitle the new album title value to set * @return {@link AlbumPage} @@ -94,7 +92,7 @@ public AlbumPage changeAlbumTitle(String albumTitle) { /** - * Sets the artist input text field + * Sets the artist input text field. * * @param artist the new artist value to set * @return {@link AlbumPage} @@ -107,7 +105,7 @@ public AlbumPage changeArtist(String artist) { /** - * Selects the select's option value based on the year value given + * Selects the select's option value based on the year value given. * * @param year the new year value to set * @return {@link AlbumPage} @@ -121,7 +119,7 @@ public AlbumPage changeAlbumYear(int year) { /** - * Sets the album rating input text field + * Sets the album rating input text field. * * @param albumRating the new album rating value to set * @return {@link AlbumPage} @@ -133,20 +131,21 @@ public AlbumPage changeAlbumRating(String albumRating) { } /** - * Sets the number of songs number input field + * Sets the number of songs number input field. * * @param numberOfSongs the new number of songs value to be set * @return {@link AlbumPage} */ public AlbumPage changeNumberOfSongs(int numberOfSongs) { - HtmlNumberInput numberOfSongsNumberField = (HtmlNumberInput) page.getElementById("numberOfSongs"); + HtmlNumberInput numberOfSongsNumberField = + (HtmlNumberInput) page.getElementById("numberOfSongs"); numberOfSongsNumberField.setText(Integer.toString(numberOfSongs)); return this; } /** - * Cancel changes made by clicking the cancel button + * Cancel changes made by clicking the cancel button. * * @return {@link AlbumListPage} */ @@ -162,7 +161,7 @@ public AlbumListPage cancelChanges() { /** - * Saves changes made by clicking the save button + * Saves changes made by clicking the save button. * * @return {@link AlbumPage} */ diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java index b139253a77fa..78d3fa329ab5 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/LoginPage.java @@ -29,7 +29,6 @@ import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; import java.io.IOException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +44,7 @@ public class LoginPage extends Page { private HtmlPage page; /** - * Constructor + * Constructor. * * @param webClient {@link WebClient} */ @@ -54,7 +53,7 @@ public LoginPage(WebClient webClient) { } /** - * Navigates to the Login page + * Navigates to the Login page. * * @return {@link LoginPage} */ @@ -77,7 +76,7 @@ public boolean isAt() { /** - * Enters the username into the username input text field + * Enters the username into the username input text field. * * @param username the username to enter * @return {@link LoginPage} @@ -90,23 +89,24 @@ public LoginPage enterUsername(String username) { /** - * Enters the password into the password input password field + * Enters the password into the password input password field. * * @param password the password to enter * @return {@link LoginPage} */ public LoginPage enterPassword(String password) { - HtmlPasswordInput passwordInputPasswordField = (HtmlPasswordInput) page.getElementById("password"); + HtmlPasswordInput passwordInputPasswordField = + (HtmlPasswordInput) page.getElementById("password"); passwordInputPasswordField.setText(password); return this; } /** - * Clicking on the login button to 'login' + * Clicking on the login button to 'login'. * - * @return {@link AlbumListPage} - * - this is the page that user gets navigated to once successfully logged in + * @return {@link AlbumListPage} - this is the page that user gets navigated to once successfully + * logged in */ public AlbumListPage login() { HtmlSubmitInput loginButton = (HtmlSubmitInput) page.getElementById("loginButton"); diff --git a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java index 78bc4618c407..ddf7ec63ed54 100644 --- a/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java +++ b/page-object/test-automation/src/main/java/com/iluwatar/pageobject/Page.java @@ -26,20 +26,19 @@ import com.gargoylesoftware.htmlunit.WebClient; /** - * Encapsulation for a generic 'Page' + * Encapsulation for a generic 'Page'. */ public abstract class Page { /** - * Application Under Test path - * This directory location is where html web pages are located + * Application Under Test path This directory location is where html web pages are located. */ public static final String AUT_PATH = "../sample-application/src/main/resources/sample-ui/"; protected final WebClient webClient; /** - * Constructor + * Constructor. * * @param webClient {@link WebClient} */ @@ -48,7 +47,7 @@ public Page(WebClient webClient) { } /** - * Checks that the current page is actually the page this page object represents + * Checks that the current page is actually the page this page object represents. * * @return true if so, otherwise false */ diff --git a/partial-response/pom.xml b/partial-response/pom.xml index bef921f0583a..6bca7007329d 100644 --- a/partial-response/pom.xml +++ b/partial-response/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java index 314846a3dbe5..5a3e7d950e0d 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java @@ -23,18 +23,16 @@ package com.iluwatar.partialresponse; +import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; - /** - * The Partial response pattern is a design pattern in which client specifies fields to fetch to serve. - * Here {@link App} is playing as client for {@link VideoResource} server. - * Client ask for specific fields information in video to server. - *

- *

- * {@link VideoResource} act as server to serve video information. + * The Partial response pattern is a design pattern in which client specifies fields to fetch to + * serve. Here {@link App} is playing as client for {@link VideoResource} server. Client ask for + * specific fields information in video to server. + * + *

{@link VideoResource} act as server to serve video information. */ public class App { @@ -47,12 +45,12 @@ public class App { */ public static void main(String[] args) throws Exception { Map videos = Map.of( - 1, new Video(1, "Avatar", 178, "epic science fiction film", - "James Cameron", "English"), - 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", - "Hideaki Anno", "Japanese"), - 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", - "Christopher Nolan", "English")); + 1, new Video(1, "Avatar", 178, "epic science fiction film", + "James Cameron", "English"), + 2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", + "Hideaki Anno", "Japanese"), + 3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", + "Christopher Nolan", "English")); VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos); diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java index da1d22620c31..f735b4d2b847 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/FieldJsonMapper.java @@ -26,11 +26,13 @@ import java.lang.reflect.Field; /** - * Map a video to json + * Map a video to json. */ public class FieldJsonMapper { /** + * Gets json of required fields from video. + * * @param video object containing video information * @param fields fields information to get * @return json of required fields from video diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java index fcfda7497f95..9e3ad5ea3ccb 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/Video.java @@ -24,8 +24,7 @@ package com.iluwatar.partialresponse; /** - * {@link Video} is a entity to serve from server.It contains all video related information.. - *

+ * {@link Video} is a entity to serve from server.It contains all video related information. */ public class Video { private final Integer id; @@ -36,23 +35,27 @@ public class Video { private final String language; /** - * @param id video unique id - * @param title video title - * @param length video length in minutes - * @param description video description by publisher - * @param director video director name - * @param language video language {private, public} + * Constructor. + * + * @param id video unique id + * @param title video title + * @param len video length in minutes + * @param desc video description by publisher + * @param director video director name + * @param lang video language {private, public} */ - public Video(Integer id, String title, Integer length, String description, String director, String language) { + public Video(Integer id, String title, Integer len, String desc, String director, String lang) { this.id = id; this.title = title; - this.length = length; - this.description = description; + this.length = len; + this.description = desc; this.director = director; - this.language = language; + this.language = lang; } /** + * ToString. + * * @return json representaion of video */ @Override diff --git a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java index d0d77af05151..a61a3c429e8a 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/VideoResource.java @@ -26,14 +26,16 @@ import java.util.Map; /** - * The resource class which serves video information. - * This class act as server in the demo. Which has all video details. + * The resource class which serves video information. This class act as server in the demo. Which + * has all video details. */ public class VideoResource { private FieldJsonMapper fieldJsonMapper; private Map videos; /** + * Constructor. + * * @param fieldJsonMapper map object to json. * @param videos initialize resource with existing videos. Act as database. */ @@ -43,6 +45,8 @@ public VideoResource(FieldJsonMapper fieldJsonMapper, Map videos } /** + * Get Details. + * * @param id video id * @param fields fields to get information about * @return full response if no fields specified else partial response for given field. diff --git a/pipeline/pom.xml b/pipeline/pom.xml index f67e6ad2df16..e7d879d4a5ce 100644 --- a/pipeline/pom.xml +++ b/pipeline/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT pipeline diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/App.java b/pipeline/src/main/java/com/iluwatar/pipeline/App.java index 3298a6eb69b2..1b1e443e6456 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/App.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/App.java @@ -24,21 +24,20 @@ package com.iluwatar.pipeline; /** - * The Pipeline pattern uses ordered stages to process a sequence of input values. - * Each implemented task is represented by a stage of the pipeline. You can think of - * pipelines as similar to assembly lines in a factory, where each item in the assembly - * line is constructed in stages. The partially assembled item is passed from one assembly - * stage to another. The outputs of the assembly line occur in the same order as that of the - * inputs. + * The Pipeline pattern uses ordered stages to process a sequence of input values. Each implemented + * task is represented by a stage of the pipeline. You can think of pipelines as similar to assembly + * lines in a factory, where each item in the assembly line is constructed in stages. The partially + * assembled item is passed from one assembly stage to another. The outputs of the assembly line + * occur in the same order as that of the inputs. * - * Classes used in this example are suffixed with "Handlers", and synonymously refers to the + *

Classes used in this example are suffixed with "Handlers", and synonymously refers to the * "stage". */ public class App { /** - * Specify the initial input type for the first stage handler and the expected output type - * of the last stage handler as type parameters for Pipeline. Use the fluent builder by - * calling addHandler to add more stage handlers on the pipeline. + * Specify the initial input type for the first stage handler and the expected output type of the + * last stage handler as type parameters for Pipeline. Use the fluent builder by calling + * addHandler to add more stage handlers on the pipeline. */ public static void main(String[] args) { /* diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java index 104d81f40b88..365fc1cdc2e4 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/ConvertToCharArrayHandler.java @@ -23,11 +23,10 @@ package com.iluwatar.pipeline; +import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Arrays; - /** * Stage handler that converts an input String to its char[] array counterpart. */ @@ -38,8 +37,10 @@ class ConvertToCharArrayHandler implements Handler { @Override public char[] process(String input) { char[] characters = input.toCharArray(); - LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", - ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class)); + LOGGER + .info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + ConvertToCharArrayHandler.class, input, String.class, Arrays + .toString(characters), Character[].class)); return characters; } diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java index 253bc22f5607..5591632e08ba 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Handler.java @@ -24,7 +24,9 @@ package com.iluwatar.pipeline; /** - * Forms a contract to all stage handlers to accept a certain type of input and return a processed output. + * Forms a contract to all stage handlers to accept a certain type of input and return a processed + * output. + * * @param the input type of the handler * @param the processed output type of the handler */ diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java index af5c69b1d77c..81b63e6cfdcf 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/Pipeline.java @@ -24,8 +24,9 @@ package com.iluwatar.pipeline; /** - * Main Pipeline class that initially sets the current handler. Processed output - * of the initial handler is then passed as the input to the next stage handlers. + * Main Pipeline class that initially sets the current handler. Processed output of the initial + * handler is then passed as the input to the next stage handlers. + * * @param the type of the input for the first stage handler * @param the final stage handler's output type */ diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java index 930332671c3d..b2ed938cf100 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveAlphabetsHandler.java @@ -27,7 +27,8 @@ import org.slf4j.LoggerFactory; /** - * Stage handler that returns a new instance of String without the alphabet characters of the input string. + * Stage handler that returns a new instance of String without the alphabet characters of the input + * string. */ class RemoveAlphabetsHandler implements Handler { @@ -47,8 +48,13 @@ public String process(String input) { } String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString(); - LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", - RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class)); + LOGGER.info( + String.format( + "Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveAlphabetsHandler.class, input, + String.class, inputWithoutAlphabetsStr, String.class + ) + ); return inputWithoutAlphabetsStr; } diff --git a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java index 6fd591006c55..450bef7177ea 100644 --- a/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java +++ b/pipeline/src/main/java/com/iluwatar/pipeline/RemoveDigitsHandler.java @@ -27,7 +27,8 @@ import org.slf4j.LoggerFactory; /** - * Stage handler that returns a new instance of String without the digit characters of the input string. + * Stage handler that returns a new instance of String without the digit characters of the input + * string. */ class RemoveDigitsHandler implements Handler { @@ -47,8 +48,9 @@ public String process(String input) { } String inputWithoutDigitsStr = inputWithoutDigits.toString(); - LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", - RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); + LOGGER + .info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", + RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); return inputWithoutDigitsStr; } diff --git a/poison-pill/pom.xml b/poison-pill/pom.xml index b10b54c008ff..b751fad04837 100644 --- a/poison-pill/pom.xml +++ b/poison-pill/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT poison-pill diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java index 6d6a41eb9970..7fdf71a09b3b 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/App.java @@ -30,16 +30,15 @@ * Pill will stop reading messages from the queue. You must also ensure that the Poison Pill will be * the last message that will be read from the queue (if you have prioritized queue then this can be * tricky). - *

- * In simple cases the Poison Pill can be just a null-reference, but holding a unique separate + * + *

In simple cases the Poison Pill can be just a null-reference, but holding a unique separate * shared object-marker (with name "Poison" or "Poison Pill") is more clear and self describing. - * */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java index 12cc246d8d28..25d2338e1226 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Consumer.java @@ -28,10 +28,10 @@ import org.slf4j.LoggerFactory; /** - * Class responsible for receiving and handling submitted to the queue messages + * Class responsible for receiving and handling submitted to the queue messages. */ public class Consumer { - + private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class); private final MqSubscribePoint queue; @@ -43,7 +43,7 @@ public Consumer(String name, MqSubscribePoint queue) { } /** - * Consume message + * Consume message. */ public void consume() { while (true) { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java index 9b35bf53a569..b0298e4077cb 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Message.java @@ -65,7 +65,7 @@ private RuntimeException poison() { }; /** - * Enumeration of Type of Headers + * Enumeration of Type of Headers. */ enum Headers { DATE, SENDER diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java index ce8005fcebaf..2928e172d5d4 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MessageQueue.java @@ -24,7 +24,7 @@ package com.iluwatar.poison.pill; /** - * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer} + * Represents abstraction of channel (or pipe) that bounds {@link Producer} and {@link Consumer}. */ public interface MessageQueue extends MqPublishPoint, MqSubscribePoint { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java index b0e086637509..f61a579872a4 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqPublishPoint.java @@ -24,7 +24,7 @@ package com.iluwatar.poison.pill; /** - * Endpoint to publish {@link Message} to queue + * Endpoint to publish {@link Message} to queue. */ public interface MqPublishPoint { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java index bb01e6395f14..b7133de8c845 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/MqSubscribePoint.java @@ -24,7 +24,7 @@ package com.iluwatar.poison.pill; /** - * Endpoint to retrieve {@link Message} from queue + * Endpoint to retrieve {@link Message} from queue. */ public interface MqSubscribePoint { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java index 0b746b31f3e7..679500e43317 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/Producer.java @@ -23,15 +23,14 @@ package com.iluwatar.poison.pill; -import java.util.Date; - import com.iluwatar.poison.pill.Message.Headers; +import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class responsible for producing unit of work that can be expressed as message and submitted to - * queue + * queue. */ public class Producer { @@ -42,7 +41,7 @@ public class Producer { private boolean isStopped; /** - * Constructor + * Constructor. */ public Producer(String name, MqPublishPoint queue) { this.name = name; @@ -51,7 +50,7 @@ public Producer(String name, MqPublishPoint queue) { } /** - * Send message to queue + * Send message to queue. */ public void send(String body) { if (isStopped) { @@ -72,7 +71,7 @@ public void send(String body) { } /** - * Stop system by sending poison pill + * Stop system by sending poison pill. */ public void stop() { isStopped = true; diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java index efc45fc83bef..8a7af515f7e8 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessage.java @@ -28,7 +28,7 @@ import java.util.Map; /** - * {@link Message} basic implementation + * {@link Message} basic implementation. */ public class SimpleMessage implements Message { diff --git a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java index 7f1b662cde71..f6a50d4ff030 100644 --- a/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java +++ b/poison-pill/src/main/java/com/iluwatar/poison/pill/SimpleMessageQueue.java @@ -27,7 +27,7 @@ import java.util.concurrent.BlockingQueue; /** - * Bounded blocking queue wrapper + * Bounded blocking queue wrapper. */ public class SimpleMessageQueue implements MessageQueue { diff --git a/pom.xml b/pom.xml index 1ab896068a6b..39582fd93718 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ 4.0.0 com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT pom 2014-2019 @@ -187,6 +187,7 @@ saga double-buffer sharding + game-loop @@ -384,9 +385,6 @@ - org.apache.maven.plugins maven-checkstyle-plugin @@ -403,7 +401,8 @@ checkstyle-suppressions.xml UTF-8 true - true + warning + false diff --git a/priority-queue/pom.xml b/priority-queue/pom.xml index 3e5ac50e81ab..3ba564b55583 100644 --- a/priority-queue/pom.xml +++ b/priority-queue/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java index 1e6e44a68564..e803489b28d2 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Application.java @@ -25,16 +25,15 @@ /** * Prioritize requests sent to services so that requests with a higher priority are received and - * processed more quickly than those of a lower priority. - * This pattern is useful in applications that offer different service level guarantees - * to individual clients. - * Example :Send multiple message with different priority to worker queue. - * Worker execute higher priority message first + * processed more quickly than those of a lower priority. This pattern is useful in applications + * that offer different service level guarantees to individual clients. Example :Send multiple + * message with different priority to worker queue. Worker execute higher priority message first + * * @see "https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn589794(v=pandp.10)" */ public class Application { /** - * main entry + * main entry. */ public static void main(String[] args) throws Exception { diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java index b874bd677915..a9a3dcfa630c 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Message.java @@ -24,7 +24,7 @@ package com.iluwatar.priority.queue; /** - * Message bean + * Message bean. */ public class Message implements Comparable { private final String message; diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java index ff73a496ff58..66f4d4f591f6 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/PriorityMessageQueue.java @@ -23,11 +23,11 @@ package com.iluwatar.priority.queue; +import static java.util.Arrays.copyOf; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static java.util.Arrays.copyOf; - /** * Keep high Priority message on top using maxHeap. * @@ -50,14 +50,14 @@ public PriorityMessageQueue(T[] queue) { } /** - * Remove top message from queue + * Remove top message from queue. */ public T remove() { if (isEmpty()) { return null; } - T root = queue[0]; + final T root = queue[0]; queue[0] = queue[size - 1]; size--; maxHeapifyDown(); @@ -65,7 +65,7 @@ public T remove() { } /** - * Add message to queue + * Add message to queue. */ public void add(T t) { ensureCapacity(); @@ -75,7 +75,7 @@ public void add(T t) { } /** - * Check queue size + * Check queue size. */ public boolean isEmpty() { return size == 0; diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java index ade211766c3d..7eca0aca6d3d 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/QueueManager.java @@ -24,7 +24,7 @@ package com.iluwatar.priority.queue; /** - * Manage priority queue + * Manage priority queue. */ public class QueueManager { /* @@ -37,7 +37,7 @@ public QueueManager(int initialCapacity) { } /** - * Publish message to queue + * Publish message to queue. */ public void publishMessage(Message message) { messagePriorityMessageQueue.add(message); @@ -45,7 +45,7 @@ public void publishMessage(Message message) { /** - * recive message from queue + * recive message from queue. */ public Message receiveMessage() { if (messagePriorityMessageQueue.isEmpty()) { diff --git a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java index bbeb64b73a7e..18ed16199584 100644 --- a/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java +++ b/priority-queue/src/main/java/com/iluwatar/priority/queue/Worker.java @@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory; /** - * Message Worker + * Message Worker. */ public class Worker { @@ -40,7 +40,7 @@ public Worker(QueueManager queueManager) { } /** - * Keep checking queue for message + * Keep checking queue for message. */ @SuppressWarnings("squid:S2189") public void run() throws Exception { @@ -56,7 +56,7 @@ public void run() throws Exception { } /** - * Process message + * Process message. */ private void processMessage(Message message) { LOGGER.info(message.toString()); diff --git a/private-class-data/pom.xml b/private-class-data/pom.xml index da9b510542c6..ecc2933d9ef7 100644 --- a/private-class-data/pom.xml +++ b/private-class-data/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT private-class-data diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java index c5b75eee4a78..367baaf8b86c 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java @@ -24,26 +24,24 @@ package com.iluwatar.privateclassdata; /** - * * The Private Class Data design pattern seeks to reduce exposure of attributes by limiting their * visibility. It reduces the number of class attributes by encapsulating them in single data * object. It allows the class designer to remove write privilege of attributes that are intended to * be set only during construction, even from methods of the target class. - *

- * In the example we have normal {@link Stew} class with some ingredients given in constructor. Then - * we have methods to enumerate the ingredients and to taste the stew. The method for tasting the - * stew alters the private members of the {@link Stew} class. - * - * The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew} - * class that contains {@link StewData}. The private data members of {@link Stew} are now in - * {@link StewData} and cannot be altered by {@link ImmutableStew} methods. * + *

In the example we have normal {@link Stew} class with some ingredients given in constructor. + * Then we have methods to enumerate the ingredients and to taste the stew. The method for tasting + * the stew alters the private members of the {@link Stew} class. + * + *

The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew} + * class that contains {@link StewData}. The private data members of {@link Stew} are now in {@link + * StewData} and cannot be altered by {@link ImmutableStew} methods. */ public class App { /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java index 627d744620bd..695424695822 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Immutable stew class, protected with Private Class Data pattern - * + * Immutable stew class, protected with Private Class Data pattern. */ public class ImmutableStew { @@ -42,10 +40,11 @@ public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPepper } /** - * Mix the stew + * Mix the stew. */ public void mix() { - LOGGER.info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", - data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()); + LOGGER + .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", + data.getNumPotatoes(), data.getNumCarrots(), data.getNumMeat(), data.getNumPeppers()); } } diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java index 6618ee5dac95..65ba6c08e568 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * Mutable stew class - * + * Mutable stew class. */ public class Stew { @@ -41,7 +39,7 @@ public class Stew { private int numPeppers; /** - * Constructor + * Constructor. */ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { this.numPotatoes = numPotatoes; @@ -51,7 +49,7 @@ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { } /** - * Mix the stew + * Mix the stew. */ public void mix() { LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", @@ -59,7 +57,7 @@ public void mix() { } /** - * Taste the stew + * Taste the stew. */ public void taste() { LOGGER.info("Tasting the stew"); diff --git a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java index c170a531ef1a..bcdaba3e9ce9 100644 --- a/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java +++ b/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java @@ -24,9 +24,7 @@ package com.iluwatar.privateclassdata; /** - * - * Stew ingredients - * + * Stew ingredients. */ public class StewData { @@ -36,7 +34,7 @@ public class StewData { private int numPeppers; /** - * Constructor + * Constructor. */ public StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { this.numPotatoes = numPotatoes; diff --git a/producer-consumer/pom.xml b/producer-consumer/pom.xml index 1cbf039103ca..479bd321aed2 100644 --- a/producer-consumer/pom.xml +++ b/producer-consumer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT producer-consumer diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java index 853c6fcfe51d..0ead44307b7d 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/App.java @@ -23,20 +23,22 @@ package com.iluwatar.producer.consumer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between - * Producer and Consumer by separating Identification of work with Execution of Work. - *

- * In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code - * producer and consumer separately. It also addresses the issue of different timing require to produce item or - * consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed. + * Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces + * coupling between Producer and Consumer by separating Identification of work with + * Execution of Work. + * + *

In producer consumer design pattern a shared queue is used to control the flow and this + * separation allows you to code producer and consumer separately. It also addresses the issue + * of different timing require to produce item or consuming item. by using producer consumer + * pattern both Producer and Consumer Thread can work with different speed. * */ public class App { @@ -44,7 +46,7 @@ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. * * @param args * command line args diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java index 3e4e9aadb3d9..5598f3e45dca 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java @@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory; /** - * Class responsible for consume the {@link Item} produced by {@link Producer} + * Class responsible for consume the {@link Item} produced by {@link Producer}. */ public class Consumer { @@ -43,12 +43,13 @@ public Consumer(String name, ItemQueue queue) { } /** - * Consume item from the queue + * Consume item from the queue. */ public void consume() throws InterruptedException { Item item = queue.take(); - LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.getId(), item.getProducer()); + LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, + item.getId(), item.getProducer()); } } diff --git a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java index e8c79afd4836..6d4ca0096d6d 100644 --- a/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java +++ b/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java @@ -27,7 +27,7 @@ /** * Class responsible for producing unit of work that can be expressed as {@link Item} and submitted - * to queue + * to queue. */ public class Producer { @@ -45,7 +45,7 @@ public Producer(String name, ItemQueue queue) { } /** - * Put item in the queue + * Put item in the queue. */ public void produce() throws InterruptedException { diff --git a/promise/pom.xml b/promise/pom.xml index 6ee49075766b..369e95748a87 100644 --- a/promise/pom.xml +++ b/promise/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT promise diff --git a/promise/src/main/java/com/iluwatar/promise/App.java b/promise/src/main/java/com/iluwatar/promise/App.java index c201d33526c2..c016b67ff0b5 100644 --- a/promise/src/main/java/com/iluwatar/promise/App.java +++ b/promise/src/main/java/com/iluwatar/promise/App.java @@ -22,8 +22,6 @@ */ package com.iluwatar.promise; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -32,10 +30,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * - * The Promise object is used for asynchronous computations. A Promise represents an operation - * that hasn't completed yet, but is expected in the future. + * The Promise object is used for asynchronous computations. A Promise represents an operation + * that hasn't completed yet, but is expected in the future. * *

A Promise represents a proxy for a value not necessarily known when the promise is created. It * allows you to associate dependent promises to an asynchronous action's eventual success value or @@ -49,15 +49,14 @@ *

  • Prevents callback hell and provides callback aggregation * * - *

    - * In this application the usage of promise is demonstrated with two examples: + *

    In this application the usage of promise is demonstrated with two examples: *

      *
    • Count Lines: In this example a file is downloaded and its line count is calculated. * The calculated line count is then consumed and printed on console. *
    • Lowest Character Frequency: In this example a file is downloaded and its lowest frequency * character is found and printed on console. This happens via a chain of promises, we start with - * a file download promise, then a promise of character frequency, then a promise of lowest frequency - * character which is finally consumed and result is printed on console. + * a file download promise, then a promise of character frequency, then a promise of lowest + * frequency character which is finally consumed and result is printed on console. *
    * * @see CompletableFuture @@ -76,7 +75,7 @@ private App() { } /** - * Program entry point + * Program entry point. * @param args arguments * @throws InterruptedException if main thread is interrupted. * @throws ExecutionException if an execution error occurs. diff --git a/promise/src/main/java/com/iluwatar/promise/Utility.java b/promise/src/main/java/com/iluwatar/promise/Utility.java index 472f7b0a5234..09c7f6ddc7b3 100644 --- a/promise/src/main/java/com/iluwatar/promise/Utility.java +++ b/promise/src/main/java/com/iluwatar/promise/Utility.java @@ -23,9 +23,6 @@ package com.iluwatar.promise; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -39,8 +36,11 @@ import java.util.Map; import java.util.Map.Entry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * Utility to perform various operations + * Utility to perform various operations. */ public class Utility { @@ -71,7 +71,8 @@ public static Map characterFrequency(String fileLocation) { } /** - * @return the character with lowest frequency if it exists, {@code Optional.empty()} otherwise. + * Return the character with the lowest frequency, if exists. + * @return the character, {@code Optional.empty()} otherwise. */ public static Character lowestFrequencyChar(Map charFrequency) { Character lowestFrequencyChar = null; @@ -92,7 +93,8 @@ public static Character lowestFrequencyChar(Map charFrequenc } /** - * @return number of lines in the file at provided location. 0 if file does not exist. + * Count the number of lines in a file. + * @return number of lines, 0 if file does not exist. */ public static Integer countLines(String fileLocation) { int lineCount = 0; diff --git a/property/pom.xml b/property/pom.xml index b04242256f0f..4e1a16a0d9f4 100644 --- a/property/pom.xml +++ b/property/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT property diff --git a/property/src/main/java/com/iluwatar/property/App.java b/property/src/main/java/com/iluwatar/property/App.java index a7045e6df6db..d37dd5fd7deb 100644 --- a/property/src/main/java/com/iluwatar/property/App.java +++ b/property/src/main/java/com/iluwatar/property/App.java @@ -28,25 +28,23 @@ import org.slf4j.LoggerFactory; /** - * * The Property pattern is also known as Prototype inheritance. - *

    - * In prototype inheritance instead of classes, as opposite to Java class inheritance, objects are - * used to create another objects and object hierarchies. Hierarchies are created using prototype - * chain through delegation: every object has link to parent object. Any base (parent) object can be - * amended at runtime (by adding or removal of some property), and all child objects will be - * affected as result. - *

    - * In this example we demonstrate {@link Character} instantiation using the Property pattern. - * + * + *

    In prototype inheritance instead of classes, as opposite to Java class inheritance, objects + * are used to create another objects and object hierarchies. Hierarchies are created using + * prototype chain through delegation: every object has link to parent object. Any base (parent) + * object can be amended at runtime (by adding or removal of some property), and all child objects + * will be affected as result. + * + *

    In this example we demonstrate {@link Character} instantiation using the Property pattern. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { diff --git a/property/src/main/java/com/iluwatar/property/Character.java b/property/src/main/java/com/iluwatar/property/Character.java index ef19f01072e6..bbe7014599f2 100644 --- a/property/src/main/java/com/iluwatar/property/Character.java +++ b/property/src/main/java/com/iluwatar/property/Character.java @@ -32,7 +32,7 @@ public class Character implements Prototype { /** - * Enumeration of Character types + * Enumeration of Character types. */ public enum Type { WARRIOR, MAGE, ROGUE @@ -45,26 +45,28 @@ public enum Type { private Type type; /** - * Constructor + * Constructor. */ public Character() { this.prototype = new Prototype() { // Null-value object - @Override - public Integer get(Stats stat) { - return null; - } - - @Override - public boolean has(Stats stat) { - return false; - } - - @Override - public void set(Stats stat, Integer val) {} - - @Override - public void remove(Stats stat) {} - }; + @Override + public Integer get(Stats stat) { + return null; + } + + @Override + public boolean has(Stats stat) { + return false; + } + + @Override + public void set(Stats stat, Integer val) { + } + + @Override + public void remove(Stats stat) { + } + }; } public Character(Type type, Prototype prototype) { @@ -73,7 +75,7 @@ public Character(Type type, Prototype prototype) { } /** - * Constructor + * Constructor. */ public Character(String name, Character prototype) { this.name = name; diff --git a/property/src/main/java/com/iluwatar/property/Prototype.java b/property/src/main/java/com/iluwatar/property/Prototype.java index 9570f66536d8..423863522acd 100644 --- a/property/src/main/java/com/iluwatar/property/Prototype.java +++ b/property/src/main/java/com/iluwatar/property/Prototype.java @@ -24,7 +24,7 @@ package com.iluwatar.property; /** - * Interface for prototype inheritance + * Interface for prototype inheritance. */ public interface Prototype { diff --git a/property/src/main/java/com/iluwatar/property/Stats.java b/property/src/main/java/com/iluwatar/property/Stats.java index 4015e5693680..2941299d5973 100644 --- a/property/src/main/java/com/iluwatar/property/Stats.java +++ b/property/src/main/java/com/iluwatar/property/Stats.java @@ -24,7 +24,7 @@ package com.iluwatar.property; /** - * All possible attributes that Character can have + * All possible attributes that Character can have. */ public enum Stats { diff --git a/prototype/pom.xml b/prototype/pom.xml index a715deb79dce..7a8a685cc260 100644 --- a/prototype/pom.xml +++ b/prototype/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT prototype diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index 457f4f2a0f5a..9b1d4eb320b3 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -27,41 +27,43 @@ import org.slf4j.LoggerFactory; /** - * * The Prototype pattern is a creational design pattern in software development. It is used when the * type of objects to create is determined by a prototypical instance, which is cloned to produce * new objects. This pattern is used to: - avoid subclasses of an object creator in the client * application, like the abstract factory pattern does. - avoid the inherent cost of creating a new * object in the standard way (e.g., using the 'new' keyword) - *

    - * In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by cloning - * the existing ones. The factory's prototype objects are given as constructor parameters. - * + * + *

    In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by + * cloning the existing ones. The factory's prototype objects are given as constructor parameters. */ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point - * + * Program entry point. + * * @param args command line args */ public static void main(String[] args) { - HeroFactory factory; - Mage mage; - Warlord warlord; - Beast beast; - - factory = new HeroFactoryImpl(new ElfMage("cooking"), new ElfWarlord("cleaning"), new ElfBeast("protecting")); - mage = factory.createMage(); - warlord = factory.createWarlord(); - beast = factory.createBeast(); + HeroFactory factory = new HeroFactoryImpl( + new ElfMage("cooking"), + new ElfWarlord("cleaning"), + new ElfBeast("protecting") + ); + Mage mage = factory.createMage(); + Warlord warlord = factory.createWarlord(); + Beast beast = factory.createBeast(); LOGGER.info(mage.toString()); LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); - factory = new HeroFactoryImpl(new OrcMage("axe"), new OrcWarlord("sword"), new OrcBeast("laser")); + factory = + new HeroFactoryImpl( + new OrcMage("axe"), + new OrcWarlord("sword"), + new OrcBeast("laser") + ); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); diff --git a/prototype/src/main/java/com/iluwatar/prototype/Beast.java b/prototype/src/main/java/com/iluwatar/prototype/Beast.java index 3b82cdd9dde1..e3b25b850d19 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Beast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Beast.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * Beast - * + * Beast. */ public abstract class Beast extends Prototype { diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java index 9ef44b164391..50761964a4ac 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java @@ -24,12 +24,10 @@ package com.iluwatar.prototype; /** - * - * ElfBeast - * + * ElfBeast. */ public class ElfBeast extends Beast { - + private String helpType; public ElfBeast(String helpType) { diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java index 14b6e6261ba6..014c39bac2e5 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfMage.java @@ -24,15 +24,13 @@ package com.iluwatar.prototype; /** - * - * ElfMage - * + * ElfMage. */ public class ElfMage extends Mage { - + private String helpType; - + public ElfMage(String helpType) { this.helpType = helpType; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java index 6c5a4a4ffc0a..43cdac7e5747 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java @@ -24,14 +24,12 @@ package com.iluwatar.prototype; /** - * - * ElfWarlord - * + * ElfWarlord. */ public class ElfWarlord extends Warlord { private String helpType; - + public ElfWarlord(String helpType) { this.helpType = helpType; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java index 791671289b4c..2644167971a1 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * * Interface for the factory class. - * */ public interface HeroFactory { diff --git a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java index 5803ee8efcc6..b9348a3b22b8 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java +++ b/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * * Concrete factory class. - * */ public class HeroFactoryImpl implements HeroFactory { @@ -35,7 +33,7 @@ public class HeroFactoryImpl implements HeroFactory { private Beast beast; /** - * Constructor + * Constructor. */ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) { this.mage = mage; @@ -44,7 +42,7 @@ public HeroFactoryImpl(Mage mage, Warlord warlord, Beast beast) { } /** - * Create mage + * Create mage. */ public Mage createMage() { try { @@ -55,7 +53,7 @@ public Mage createMage() { } /** - * Create warlord + * Create warlord. */ public Warlord createWarlord() { try { @@ -66,7 +64,7 @@ public Warlord createWarlord() { } /** - * Create beast + * Create beast. */ public Beast createBeast() { try { diff --git a/prototype/src/main/java/com/iluwatar/prototype/Mage.java b/prototype/src/main/java/com/iluwatar/prototype/Mage.java index 9da5e45baada..27c3bae7a191 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Mage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Mage.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * Mage - * + * Mage. */ public abstract class Mage extends Prototype { diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java index 2b5fb51599d0..c800b3ac51e6 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java @@ -24,18 +24,16 @@ package com.iluwatar.prototype; /** - * - * OrcBeast - * + * OrcBeast. */ public class OrcBeast extends Beast { - + private String weapon; public OrcBeast(String weapon) { this.weapon = weapon; } - + public OrcBeast(OrcBeast orcBeast) { this.weapon = orcBeast.weapon; } @@ -49,6 +47,6 @@ public Beast copy() { public String toString() { return "Orcish wolf attacks with " + weapon; } - + } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java index de15b5e10d91..c71b59d06c54 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcMage.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * OrcMage - * + * OrcMage. */ public class OrcMage extends Mage { @@ -35,7 +33,7 @@ public class OrcMage extends Mage { public OrcMage(String weapon) { this.weapon = weapon; } - + public OrcMage(OrcMage orcMage) { this.weapon = orcMage.weapon; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java index 0b117357fd82..096fd49dc9c0 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * OrcWarlord - * + * OrcWarlord. */ public class OrcWarlord extends Warlord { @@ -35,7 +33,7 @@ public class OrcWarlord extends Warlord { public OrcWarlord(String weapon) { this.weapon = weapon; } - + public OrcWarlord(OrcWarlord orcWarlord) { this.weapon = orcWarlord.weapon; } diff --git a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java index bae58b026d3e..c74c82f4ad6b 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Prototype.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Prototype.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * Prototype - * + * Prototype. */ public abstract class Prototype implements Cloneable { diff --git a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java index 7ce8922e909c..c270ab80bd0d 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/Warlord.java +++ b/prototype/src/main/java/com/iluwatar/prototype/Warlord.java @@ -24,9 +24,7 @@ package com.iluwatar.prototype; /** - * - * Warlord - * + * Warlord. */ public abstract class Warlord extends Prototype { diff --git a/proxy/pom.xml b/proxy/pom.xml index e1df3657a6fa..e08c6ad87b51 100644 --- a/proxy/pom.xml +++ b/proxy/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT proxy diff --git a/proxy/src/main/java/com/iluwatar/proxy/App.java b/proxy/src/main/java/com/iluwatar/proxy/App.java index 4c9d0efaa3f4..ff02a6074fec 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/App.java +++ b/proxy/src/main/java/com/iluwatar/proxy/App.java @@ -24,25 +24,23 @@ package com.iluwatar.proxy; /** - * * A proxy, in its most general form, is a class functioning as an interface to something else. The * proxy could interface to anything: a network connection, a large object in memory, a file, or * some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper * or agent object that is being called by the client to access the real serving object behind the * scenes. - *

    - * The Proxy design pattern allows you to provide an interface to other objects by creating a + * + *

    The Proxy design pattern allows you to provide an interface to other objects by creating a * wrapper class as the proxy. The wrapper class, which is the proxy, can add additional * functionality to the object of interest without changing the object's code. - *

    - * In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object ( + * + *

    In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object ( * {@link IvoryTower}). - * */ public class App { /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { diff --git a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java index 3adb96d86b6c..658b19949080 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java +++ b/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * The object to be proxyed. - * */ public class IvoryTower implements WizardTower { diff --git a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java index 031ab8dfd2da..fc77d80df28c 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/Wizard.java +++ b/proxy/src/main/java/com/iluwatar/proxy/Wizard.java @@ -24,9 +24,7 @@ package com.iluwatar.proxy; /** - * - * Wizard - * + * Wizard. */ public class Wizard { diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java index ac83aa6ea54a..c08b49e7dcbb 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java @@ -24,7 +24,7 @@ package com.iluwatar.proxy; /** - * WizardTower interface + * WizardTower interface. */ public interface WizardTower { diff --git a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java index 7e6b2acf06d9..e295850de876 100644 --- a/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java +++ b/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * The proxy controlling access to the {@link IvoryTower}. - * */ public class WizardTowerProxy implements WizardTower { diff --git a/queue-load-leveling/pom.xml b/queue-load-leveling/pom.xml index be8404c2da25..b77466934933 100644 --- a/queue-load-leveling/pom.xml +++ b/queue-load-leveling/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT queue-load-leveling diff --git a/reactor/pom.xml b/reactor/pom.xml index 104b52521975..7610804309e5 100644 --- a/reactor/pom.xml +++ b/reactor/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT reactor diff --git a/reader-writer-lock/pom.xml b/reader-writer-lock/pom.xml index 9cde49e389c5..3892e5c62fee 100644 --- a/reader-writer-lock/pom.xml +++ b/reader-writer-lock/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT reader-writer-lock diff --git a/repository/pom.xml b/repository/pom.xml index 906389282945..3bae29a70ba9 100644 --- a/repository/pom.xml +++ b/repository/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT repository diff --git a/resource-acquisition-is-initialization/pom.xml b/resource-acquisition-is-initialization/pom.xml index d094eff8d052..c368d1b531cc 100644 --- a/resource-acquisition-is-initialization/pom.xml +++ b/resource-acquisition-is-initialization/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT resource-acquisition-is-initialization diff --git a/retry/pom.xml b/retry/pom.xml index 73b25b64b9ee..d1dc9531f71b 100644 --- a/retry/pom.xml +++ b/retry/pom.xml @@ -28,7 +28,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT retry jar diff --git a/role-object/pom.xml b/role-object/pom.xml index c9feb1419afd..322122897394 100644 --- a/role-object/pom.xml +++ b/role-object/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT role-object diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java index b8296dabacc6..eb76ef34a522 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java @@ -20,13 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; +import static com.iluwatar.roleobject.Role.Borrower; +import static com.iluwatar.roleobject.Role.Investor; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.iluwatar.roleobject.Role.*; - /** * The Role Object pattern suggests to model context-specific views * of an object as separate role objects which are @@ -39,55 +41,60 @@ * investor, respectively. Both roles could as well be played by a single {@link Customer} object. * The common superclass for customer-specific roles is provided by {@link CustomerRole}, * which also supports the {@link Customer} interface. - *

    - * The {@link CustomerRole} class is abstract and not meant to be instantiated. - * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link InvestorRole}, - * define and implement the interface for specific roles. It is only + * + *

    The {@link CustomerRole} class is abstract and not meant to be instantiated. + * Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} + * or {@link InvestorRole}, define and implement the interface for specific roles. It is only * these subclasses which are instantiated at runtime. - * The {@link BorrowerRole} class defines the context-specific view of {@link Customer} objects as needed by the loan department. + * The {@link BorrowerRole} class defines the context-specific view of {@link Customer} + * objects as needed by the loan department. * It defines additional operations to manage the customer’s * credits and securities. Similarly, the {@link InvestorRole} class adds operations specific * to the investment department’s view of customers. - * A client like the loan application may either work with objects of the {@link CustomerRole} class, using the interface class - * {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the loan application knows a particular - * {@link Customer} instance through its {@link Customer} interface. The loan application may want to check whether the {@link Customer} - * object plays the role of Borrower. - * To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For the purpose of - * our example, let’s assume we can name roles with enum. - * If the {@link Customer} object can play the role named “Borrower,” the loan application will ask it - * to return a reference to the corresponding object. + * A client like the loan application may either work with objects of the {@link CustomerRole} + * class, using the interface class {@link Customer}, or with objects of concrete + * {@link CustomerRole} subclasses. Suppose the loan application knows a particular + * {@link Customer} instance through its {@link Customer} interface. The loan application + * may want to check whether the {@link Customer} object plays the role of Borrower. + * To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For + * the purpose of our example, let’s assume we can name roles with enum. + * If the {@link Customer} object can play the role named “Borrower,” the loan application will + * ask it to return a reference to the corresponding object. * The loan application may now use this reference to call Borrower-specific operations. */ public class ApplicationRoleObject { - private static final Logger logger = LoggerFactory.getLogger(Role.class); - - public static void main(String[] args) { - Customer customer = Customer.newCustomer(Borrower, Investor); - - logger.info(" the new customer created : {}", customer); + private static final Logger logger = LoggerFactory.getLogger(Role.class); - boolean hasBorrowerRole = customer.hasRole(Borrower); - logger.info(" customer has a borrowed role - {}", hasBorrowerRole); - boolean hasInvestorRole = customer.hasRole(Investor); - logger.info(" customer has an investor role - {}", hasInvestorRole); + /** + * Main entry point. + * + * @param args program arguments + */ + public static void main(String[] args) { + Customer customer = Customer.newCustomer(Borrower, Investor); - customer.getRole(Investor, InvestorRole.class) - .ifPresent(inv -> { - inv.setAmountToInvest(1000); - inv.setName("Billy"); - }); - customer.getRole(Borrower, BorrowerRole.class) - .ifPresent(inv -> inv.setName("Johny")); + logger.info(" the new customer created : {}", customer); - customer.getRole(Investor, InvestorRole.class) - .map(InvestorRole::invest) - .ifPresent(logger::info); + boolean hasBorrowerRole = customer.hasRole(Borrower); + logger.info(" customer has a borrowed role - {}", hasBorrowerRole); + boolean hasInvestorRole = customer.hasRole(Investor); + logger.info(" customer has an investor role - {}", hasInvestorRole); - customer.getRole(Borrower, BorrowerRole.class) - .map(BorrowerRole::borrow) - .ifPresent(logger::info); - } + customer.getRole(Investor, InvestorRole.class) + .ifPresent(inv -> { + inv.setAmountToInvest(1000); + inv.setName("Billy"); + }); + customer.getRole(Borrower, BorrowerRole.class) + .ifPresent(inv -> inv.setName("Johny")); + customer.getRole(Investor, InvestorRole.class) + .map(InvestorRole::invest) + .ifPresent(logger::info); + customer.getRole(Borrower, BorrowerRole.class) + .map(BorrowerRole::borrow) + .ifPresent(logger::info); + } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java index 425d9511d083..19db1c823a79 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java @@ -20,21 +20,23 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; -public class BorrowerRole extends CustomerRole{ - private String name; +public class BorrowerRole extends CustomerRole { + + private String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String borrow(){ - return String.format("Borrower %s wants to get some money.",name); - } + public String borrow() { + return String.format("Borrower %s wants to get some money.", name); + } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java index ebcddff4b154..1d21c5cc80a9 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Customer.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -20,6 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; import java.util.Optional; @@ -29,51 +30,52 @@ */ public abstract class Customer { - /** - * Add specific role @see {@link Role} - * - * @param role to add - * @return true if the operation has been successful otherwise false - */ - public abstract boolean addRole(Role role); + /** + * Add specific role @see {@link Role}. + * @param role to add + * @return true if the operation has been successful otherwise false + */ + public abstract boolean addRole(Role role); - /** - * Check specific role @see {@link Role} - * - * @param role to check - * @return true if the role exists otherwise false - */ + /** + * Check specific role @see {@link Role}. + * @param role to check + * @return true if the role exists otherwise false + */ - public abstract boolean hasRole(Role role); + public abstract boolean hasRole(Role role); - /** - * Remove specific role @see {@link Role} - * - * @param role to remove - * @return true if the operation has been successful otherwise false - */ - public abstract boolean remRole(Role role); + /** + * Remove specific role @see {@link Role}. + * @param role to remove + * @return true if the operation has been successful otherwise false + */ + public abstract boolean remRole(Role role); - /** - * Get specific instance associated with this role @see {@link Role} - * - * @param role to get - * @param expectedRole instance class expected to get - * @return optional with value if the instance exists and corresponds expected class - */ - public abstract Optional getRole(Role role, Class expectedRole); + /** + * Get specific instance associated with this role @see {@link Role}. + * @param role to get + * @param expectedRole instance class expected to get + * @return optional with value if the instance exists and corresponds expected class + */ + public abstract Optional getRole(Role role, Class expectedRole); - public static Customer newCustomer() { - return new CustomerCore(); - } + public static Customer newCustomer() { + return new CustomerCore(); + } - public static Customer newCustomer(Role... role) { - Customer customer = newCustomer(); - for (Role r : role) { - customer.addRole(r); - } - return customer; + /** + * Create {@link Customer} with given roles. + * @param role roles + * @return Customer + */ + public static Customer newCustomer(Role... role) { + Customer customer = newCustomer(); + for (Role r : role) { + customer.addRole(r); } + return customer; + } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java index 5de27aa9295d..670a53904ef7 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -20,56 +20,60 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; /** - * Core class to store different customer roles + * Core class to store different customer roles. * - * @see CustomerRole - * Note: not thread safe + * @see CustomerRole Note: not thread safe */ public class CustomerCore extends Customer { - private Map roles; + private Map roles; - public CustomerCore() { - roles = new HashMap<>(); - } + public CustomerCore() { + roles = new HashMap<>(); + } - @Override - public boolean addRole(Role role) { - return role - .instance() - .map(inst -> { - roles.put(role, inst); - return true; - }) - .orElse(false); - } + @Override + public boolean addRole(Role role) { + return role + .instance() + .map(inst -> { + roles.put(role, inst); + return true; + }) + .orElse(false); + } - @Override - public boolean hasRole(Role role) { - return roles.containsKey(role); - } + @Override + public boolean hasRole(Role role) { + return roles.containsKey(role); + } - @Override - public boolean remRole(Role role) { - return Objects.nonNull(roles.remove(role)); - } + @Override + public boolean remRole(Role role) { + return Objects.nonNull(roles.remove(role)); + } - @Override - public Optional getRole(Role role, Class expectedRole) { - return Optional - .ofNullable(roles.get(role)) - .filter(expectedRole::isInstance) - .map(expectedRole::cast); - } + @Override + public Optional getRole(Role role, Class expectedRole) { + return Optional + .ofNullable(roles.get(role)) + .filter(expectedRole::isInstance) + .map(expectedRole::cast); + } - @Override - public String toString() { - String roles = Arrays.toString(this.roles.keySet().toArray()); - return "Customer{roles=" + roles + "}"; - } + @Override + public String toString() { + String roles = Arrays.toString(this.roles.keySet().toArray()); + return "Customer{roles=" + roles + "}"; + } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java index 40fe2341b3a9..7f1805924fdc 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -20,9 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; /** - * Key abstraction for segregated roles + * Key abstraction for segregated roles. */ -public abstract class CustomerRole extends CustomerCore{} +public abstract class CustomerRole extends CustomerCore{ +} diff --git a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java index d6ec6bc42050..d95289a07140 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java @@ -20,29 +20,32 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; public class InvestorRole extends CustomerRole { - private String name; - private long amountToInvest; - public String getName() { - return name; - } + private String name; + + private long amountToInvest; + + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public long getAmountToInvest() { - return amountToInvest; - } + public long getAmountToInvest() { + return amountToInvest; + } - public void setAmountToInvest(long amountToInvest) { - this.amountToInvest = amountToInvest; - } + public void setAmountToInvest(long amountToInvest) { + this.amountToInvest = amountToInvest; + } - public String invest() { - return String.format("Investor %s has invested %d dollars", name, amountToInvest); - } + public String invest() { + return String.format("Investor %s has invested %d dollars", name, amountToInvest); + } } diff --git a/role-object/src/main/java/com/iluwatar/roleobject/Role.java b/role-object/src/main/java/com/iluwatar/roleobject/Role.java index f6c739891566..74863ad84051 100644 --- a/role-object/src/main/java/com/iluwatar/roleobject/Role.java +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -20,36 +20,41 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package com.iluwatar.roleobject; +import java.util.Optional; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Optional; - /** - * Possible roles + * Possible roles. */ public enum Role { - Borrower(BorrowerRole.class), Investor(InvestorRole.class); - private Class typeCst; + Borrower(BorrowerRole.class), Investor(InvestorRole.class); - Role(Class typeCst) { - this.typeCst = typeCst; - } + private Class typeCst; + + Role(Class typeCst) { + this.typeCst = typeCst; + } + + private static final Logger logger = LoggerFactory.getLogger(Role.class); - private static final Logger logger = LoggerFactory.getLogger(Role.class); - - @SuppressWarnings("unchecked") - public Optional instance() { - Class typeCst = this.typeCst; - try { - return (Optional) Optional.of(typeCst.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - logger.error("error creating an object", e); - } - return Optional.empty(); + /** + * Get instance. + */ + @SuppressWarnings("unchecked") + public Optional instance() { + Class typeCst = this.typeCst; + try { + return (Optional) Optional.of(typeCst.newInstance()); + } catch (InstantiationException | IllegalAccessException e) { + logger.error("error creating an object", e); } + return Optional.empty(); + } } diff --git a/saga/pom.xml b/saga/pom.xml index 111f4e7b8134..a22ec9797f61 100644 --- a/saga/pom.xml +++ b/saga/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT saga diff --git a/semaphore/pom.xml b/semaphore/pom.xml index 1ae865f02442..2684289981fa 100644 --- a/semaphore/pom.xml +++ b/semaphore/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT semaphore diff --git a/servant/pom.xml b/servant/pom.xml index e8c791d613be..db5abe580025 100644 --- a/servant/pom.xml +++ b/servant/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT servant diff --git a/serverless/pom.xml b/serverless/pom.xml index 292df78c55f1..1fb55ec47536 100644 --- a/serverless/pom.xml +++ b/serverless/pom.xml @@ -31,7 +31,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT diff --git a/service-layer/pom.xml b/service-layer/pom.xml index 31fc6f625b68..809454907b10 100644 --- a/service-layer/pom.xml +++ b/service-layer/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT service-layer diff --git a/service-locator/pom.xml b/service-locator/pom.xml index 5232bbd28818..56a11da10b3f 100644 --- a/service-locator/pom.xml +++ b/service-locator/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT service-locator diff --git a/sharding/README.md b/sharding/README.md index b40f08cfccd5..3184e405ed17 100644 --- a/sharding/README.md +++ b/sharding/README.md @@ -1,10 +1,9 @@ - ---- +--- layout: pattern title: Sharding -folder: sharding +folder: sharding permalink: /patterns/sharding/ -categories: Other +categories: Other tags: - Java - Difficulty-Beginner diff --git a/sharding/pom.xml b/sharding/pom.xml index f0dd01a7c8a2..eb24071fa4d5 100644 --- a/sharding/pom.xml +++ b/sharding/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/singleton/pom.xml b/singleton/pom.xml index c07183c7fae7..7862cd2a090b 100644 --- a/singleton/pom.xml +++ b/singleton/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT singleton diff --git a/spatial-partition/README.md b/spatial-partition/README.md index e4270e50b1e0..6e55f9544ff2 100644 --- a/spatial-partition/README.md +++ b/spatial-partition/README.md @@ -3,7 +3,7 @@ layout: pattern title: Spatial Partition folder: spatial-partition permalink: /patterns/spatial-partition/ -categories: Game Programming pattern/Optimisation pattern +categories: Other tags: - Java - Difficulty-Intermediate diff --git a/spatial-partition/pom.xml b/spatial-partition/pom.xml index b7d6d4b633b3..4b048714de72 100644 --- a/spatial-partition/pom.xml +++ b/spatial-partition/pom.xml @@ -46,7 +46,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT spatial-partition diff --git a/specification/README.md b/specification/README.md index a72e253d7e9b..1764f448bb78 100644 --- a/specification/README.md +++ b/specification/README.md @@ -31,7 +31,8 @@ Use the Specification pattern when Real world example -> There is a pool of different creatures and we often need to select some subset of them. We can write our search specification such as "creatures that can fly" and give it to the party that will perform the filtering. +> There is a pool of different creatures and we often need to select some subset of them. +> We can write our search specification such as "creatures that can fly", "creatures heavier than 500 kilograms", or as a combination of other search specifications, and then give it to the party that will perform the filtering. In Plain Words @@ -44,6 +45,10 @@ Wikipedia says **Programmatic Example** If we look at our creature pool example from above, we have a set of creatures with certain properties. +Those properties can be part of a pre-defined, limited set (represented here by the enums Size, Movement and Color); but they can also be continuous values (e.g. the mass of a Creature). +In this case, it is more appropriate to use what we call "parameterized specification", where the property value can be given as an argument when the Creature is instantiated, allowing for more flexibility. +A third option is to combine pre-defined and/or parameterized properties using boolean logic, allowing for near-endless selection possibilities (this is called "composite specification", see below). +The pros and cons of each approach are detailed in the table at the end of this document. ```java public interface Creature { @@ -51,24 +56,25 @@ public interface Creature { Size getSize(); Movement getMovement(); Color getColor(); + Mass getMass(); } ``` -And dragon implementation looks like this. +And ``Dragon`` implementation looks like this. ```java public class Dragon extends AbstractCreature { public Dragon() { - super("Dragon", Size.LARGE, Movement.FLYING, Color.RED); + super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, new Mass(39300.0)); } } ``` -Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use MovementSelector. +Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use ``MovementSelector``. ```java -public class MovementSelector implements Predicate { +public class MovementSelector extends AbstractSelector { private final Movement movement; @@ -83,13 +89,107 @@ public class MovementSelector implements Predicate { } ``` -With these building blocks in place, we can perform a search for red and flying creatures like this. +On the other hand, when selecting creatures heavier than a chosen amount, we use ``MassGreaterThanSelector``. ```java - List redAndFlyingCreatures = creatures.stream() - .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))).collect(Collectors.toList()); +public class MassGreaterThanSelector extends AbstractSelector { + + private final Mass mass; + + public MassGreaterThanSelector(double mass) { + this.mass = new Mass(mass); + } + + @Override + public boolean test(Creature t) { + return t.getMass().greaterThan(mass); + } +} +``` + +With these building blocks in place, we can perform a search for red creatures as follows: + +```java + List redCreatures = creatures.stream().filter(new ColorSelector(Color.RED)) + .collect(Collectors.toList()); ``` +But we could also use our parameterized selector like this: + +```java + List heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0) + .collect(Collectors.toList()); +``` + +Our third option is to combine multiple selectors together. Performing a search for special creatures (defined as red, flying, and not small) could be done as follows: + +```java + AbstractSelector specialCreaturesSelector = + new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)).and(new SizeSelector(Size.SMALL).not()); + + List specialCreatures = creatures.stream().filter(specialCreaturesSelector) + .collect(Collectors.toList()); +``` + +**More on Composite Specification** + +In Composite Specification, we will create custom instances of ``AbstractSelector`` by combining other selectors (called "leaves") using the three basic logical operators. +These are implemented in ``ConjunctionSelector``, ``DisjunctionSelector`` and ``NegationSelector``. + +```java +public abstract class AbstractSelector implements Predicate { + + public AbstractSelector and(AbstractSelector other) { + return new ConjunctionSelector<>(this, other); + } + + public AbstractSelector or(AbstractSelector other) { + return new DisjunctionSelector<>(this, other); + } + + public AbstractSelector not() { + return new NegationSelector<>(this); + } +} +``` + +```java +public class ConjunctionSelector extends AbstractSelector { + + private List> leafComponents; + + @SafeVarargs + ConjunctionSelector(AbstractSelector... selectors) { + this.leafComponents = List.of(selectors); + } + + /** + * Tests if *all* selectors pass the test. + */ + @Override + public boolean test(T t) { + return leafComponents.stream().allMatch(comp -> (comp.test(t))); + } +} +``` + +All that is left to do is now to create leaf selectors (be it hard-coded or parameterized ones) that are as generic as possible, +and we will be able to instantiate the ``AbstractSelector`` class by combining any amount of selectors, as exemplified above. +We should be careful though, as it is easy to make a mistake when combining many logical operators; in particular, we should pay attention to the priority of the operations.\ +In general, Composite Specification is a great way to write more reusable code, as there is no need to create a Selector class for each filtering operation. +Instead, we just create an instance of ``AbstractSelector`` "on the spot", using tour generic "leaf" selectors and some basic boolean logic. + + +**Comparison of the different approaches** + +| Pattern | Usage | Pros | Cons | +|---|---|---|---| +| Hard-Coded Specification | Selection criteria are few and known in advance | + Easy to implement | - Inflexible | +| | | + Expressive | +| Parameterized Specification | Selection criteria are a large range of values (e.g. mass, speed,...) | + Some flexibility | - Still requires special-purpose classes | +| Composite Specification | There are a lot of selection criteria that can be combined in multiple ways, hence it is not feasible to create a class for each selector | + Very flexible, without requiring many specialized classes | - Somewhat more difficult to comprehend | +| | | + Supports logical operations | - You still need to create the base classes used as leaves | + ## Related patterns * Repository diff --git a/specification/etc/specification.ucls b/specification/etc/specification.ucls index 2edbbed0c9cd..54b08cc41d57 100644 --- a/specification/etc/specification.ucls +++ b/specification/etc/specification.ucls @@ -117,7 +117,7 @@ - + @@ -126,7 +126,7 @@ - + @@ -186,13 +186,13 @@ - - + + - - - - + + + + @@ -202,7 +202,7 @@ - + diff --git a/specification/pom.xml b/specification/pom.xml index 9f64b41d71b7..79d81fd5c3a8 100644 --- a/specification/pom.xml +++ b/specification/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT specification diff --git a/specification/src/main/java/com/iluwatar/specification/app/App.java b/specification/src/main/java/com/iluwatar/specification/app/App.java index 8ca7283c9216..2f9633313d83 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -32,7 +32,11 @@ import com.iluwatar.specification.creature.Troll; import com.iluwatar.specification.property.Color; import com.iluwatar.specification.property.Movement; +import com.iluwatar.specification.selector.AbstractSelector; import com.iluwatar.specification.selector.ColorSelector; +import com.iluwatar.specification.selector.MassEqualSelector; +import com.iluwatar.specification.selector.MassGreaterThanSelector; +import com.iluwatar.specification.selector.MassSmallerThanOrEqSelector; import com.iluwatar.specification.selector.MovementSelector; import java.util.List; import java.util.stream.Collectors; @@ -51,7 +55,7 @@ *

    http://martinfowler.com/apsupp/spec.pdf

    */ public class App { - + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** @@ -61,6 +65,8 @@ public static void main(String[] args) { // initialize creatures list List creatures = List.of(new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), new KillerBee()); + // so-called "hard-coded" specification + LOGGER.info("Demonstrating hard-coded specification :"); // find all walking creatures LOGGER.info("Find all walking creatures"); List walkingCreatures = @@ -72,6 +78,26 @@ public static void main(String[] args) { List darkCreatures = creatures.stream().filter(new ColorSelector(Color.DARK)).collect(Collectors.toList()); darkCreatures.forEach(c -> LOGGER.info(c.toString())); + + LOGGER.info("\n"); + // so-called "parameterized" specification + LOGGER.info("Demonstrating parameterized specification :"); + // find all creatures heavier than 500kg + LOGGER.info("Find all creatures heavier than 600kg"); + List heavyCreatures = + creatures.stream().filter(new MassGreaterThanSelector(600.0)) + .collect(Collectors.toList()); + heavyCreatures.forEach(c -> LOGGER.info(c.toString())); + // find all creatures heavier than 500kg + LOGGER.info("Find all creatures lighter than or weighing exactly 500kg"); + List lightCreatures = + creatures.stream().filter(new MassSmallerThanOrEqSelector(500.0)) + .collect(Collectors.toList()); + lightCreatures.forEach(c -> LOGGER.info(c.toString())); + + LOGGER.info("\n"); + // so-called "composite" specification + LOGGER.info("Demonstrating composite specification :"); // find all red and flying creatures LOGGER.info("Find all red and flying creatures"); List redAndFlyingCreatures = @@ -79,5 +105,15 @@ public static void main(String[] args) { .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))) .collect(Collectors.toList()); redAndFlyingCreatures.forEach(c -> LOGGER.info(c.toString())); + // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg + LOGGER.info("Find all scary creatures"); + AbstractSelector scaryCreaturesSelector = new ColorSelector(Color.DARK) + .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not()) + .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); + List scaryCreatures = + creatures.stream() + .filter(scaryCreaturesSelector) + .collect(Collectors.toList()); + scaryCreatures.forEach(c -> LOGGER.info(c.toString())); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java index de7a41417efa..6b359d8ac2b1 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -36,20 +37,23 @@ public abstract class AbstractCreature implements Creature { private Size size; private Movement movement; private Color color; + private Mass mass; /** * Constructor. */ - public AbstractCreature(String name, Size size, Movement movement, Color color) { + public AbstractCreature(String name, Size size, Movement movement, Color color, Mass mass) { this.name = name; this.size = size; this.movement = movement; this.color = color; + this.mass = mass; } @Override public String toString() { - return String.format("%s [size=%s, movement=%s, color=%s]", name, size, movement, color); + return String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", + name, size, movement, color, mass); } @Override @@ -71,4 +75,9 @@ public Movement getMovement() { public Color getColor() { return color; } + + @Override + public Mass getMass() { + return mass; + } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Creature.java b/specification/src/main/java/com/iluwatar/specification/creature/Creature.java index 3f8ccdfdb259..2eb41a6dccf3 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Creature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Creature.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -39,4 +40,6 @@ public interface Creature { Movement getMovement(); Color getColor(); + + Mass getMass(); } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java b/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java index d4f5a7f23164..937bd5497a1f 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class Dragon extends AbstractCreature { public Dragon() { - super("Dragon", Size.LARGE, Movement.FLYING, Color.RED); + this(new Mass(39300.0)); + } + + public Dragon(Mass mass) { + super("Dragon", Size.LARGE, Movement.FLYING, Color.RED, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java b/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java index 0b145b737b87..7b173d580cd6 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class Goblin extends AbstractCreature { public Goblin() { - super("Goblin", Size.SMALL, Movement.WALKING, Color.GREEN); + this(new Mass(30.0)); + } + + public Goblin(Mass mass) { + super("Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java b/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java index 77f32c9f48ba..2b35714fc4f8 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class KillerBee extends AbstractCreature { public KillerBee() { - super("KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT); + this(new Mass(6.7)); + } + + public KillerBee(Mass mass) { + super("KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java b/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java index 6958f7fbd658..f516a6dc562e 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class Octopus extends AbstractCreature { public Octopus() { - super("Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK); + this(new Mass(12.0)); + } + + public Octopus(Mass mass) { + super("Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Shark.java b/specification/src/main/java/com/iluwatar/specification/creature/Shark.java index b9e161da43ee..8788e85d71bd 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Shark.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Shark.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class Shark extends AbstractCreature { public Shark() { - super("Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT); + this(new Mass(500.0)); + } + + public Shark(Mass mass) { + super("Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/creature/Troll.java b/specification/src/main/java/com/iluwatar/specification/creature/Troll.java index 3f416bdd1ed3..addcb94b62cd 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Troll.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Troll.java @@ -24,6 +24,7 @@ package com.iluwatar.specification.creature; import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; @@ -33,6 +34,10 @@ public class Troll extends AbstractCreature { public Troll() { - super("Troll", Size.LARGE, Movement.WALKING, Color.DARK); + this(new Mass(4000.0)); + } + + public Troll(Mass mass) { + super("Troll", Size.LARGE, Movement.WALKING, Color.DARK, mass); } } diff --git a/specification/src/main/java/com/iluwatar/specification/property/Color.java b/specification/src/main/java/com/iluwatar/specification/property/Color.java index 00f7007ff713..6e96b5813e71 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Color.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Color.java @@ -24,7 +24,7 @@ package com.iluwatar.specification.property; /** - *

    Color property.

    + * Color property. */ public enum Color { diff --git a/specification/src/main/java/com/iluwatar/specification/property/Mass.java b/specification/src/main/java/com/iluwatar/specification/property/Mass.java new file mode 100644 index 000000000000..b2d6ddc66f5f --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/property/Mass.java @@ -0,0 +1,67 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.property; + +/** + * Mass property. + */ +public class Mass { + + private double value; + private String title; + + public Mass(double value) { + this.value = value; + this.title = value + "kg"; // Implicit call to Double.toString(value) + } + + public final boolean greaterThan(Mass other) { + return this.value > other.value; + } + + public final boolean smallerThan(Mass other) { + return this.value < other.value; + } + + public final boolean greaterThanOrEq(Mass other) { + return this.value >= other.value; + } + + public final boolean smallerThanOrEq(Mass other) { + return this.value <= other.value; + } + + @Override + public String toString() { + return title; + } + + @Override + public final boolean equals(Object obj) { + if (!(obj instanceof Mass)) { + return false; + } + return ((Mass) obj).value == this.value; + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java new file mode 100644 index 000000000000..2dea52271152 --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/AbstractSelector.java @@ -0,0 +1,44 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import java.util.function.Predicate; + +/** + * Base class for selectors. + */ +public abstract class AbstractSelector implements Predicate { + + public AbstractSelector and(AbstractSelector other) { + return new ConjunctionSelector<>(this, other); + } + + public AbstractSelector or(AbstractSelector other) { + return new DisjunctionSelector<>(this, other); + } + + public AbstractSelector not() { + return new NegationSelector<>(this); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java index 93caf612ff92..cefa5f92ec2a 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java @@ -25,12 +25,11 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; -import java.util.function.Predicate; /** * Color selector. */ -public class ColorSelector implements Predicate { +public class ColorSelector extends AbstractSelector { private final Color color; diff --git a/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java new file mode 100644 index 000000000000..bd29aa2603b7 --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/ConjunctionSelector.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import java.util.List; + +/** + * A Selector defined as the conjunction (AND) of other (leaf) selectors. + */ +public class ConjunctionSelector extends AbstractSelector { + + private List> leafComponents; + + @SafeVarargs + ConjunctionSelector(AbstractSelector... selectors) { + this.leafComponents = List.of(selectors); + } + + /** + * Tests if *all* selectors pass the test. + */ + @Override + public boolean test(T t) { + return leafComponents.stream().allMatch(comp -> (comp.test(t))); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java new file mode 100644 index 000000000000..1fb38a43dc5b --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/DisjunctionSelector.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import java.util.List; + +/** + * A Selector defined as the disjunction (OR) of other (leaf) selectors. + */ +public class DisjunctionSelector extends AbstractSelector { + + private List> leafComponents; + + @SafeVarargs + DisjunctionSelector(AbstractSelector... selectors) { + this.leafComponents = List.of(selectors); + } + + /** + * Tests if *at least one* selector passes the test. + */ + @Override + public boolean test(T t) { + return leafComponents.stream().anyMatch(comp -> comp.test(t)); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java new file mode 100644 index 000000000000..e2c0c1e7cf0a --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassEqualSelector.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Mass; + +/** + * Mass selector for values exactly equal than the parameter. + */ +public class MassEqualSelector extends AbstractSelector { + + private final Mass mass; + + /** + * The use of a double as a parameter will spare some typing when instantiating this class. + */ + public MassEqualSelector(double mass) { + this.mass = new Mass(mass); + } + + @Override + public boolean test(Creature t) { + return t.getMass().equals(mass); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java new file mode 100644 index 000000000000..56160c12ad58 --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassGreaterThanSelector.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Mass; + +/** + * Mass selector for values greater than the parameter. + */ +public class MassGreaterThanSelector extends AbstractSelector { + + private final Mass mass; + + /** + * The use of a double as a parameter will spare some typing when instantiating this class. + */ + public MassGreaterThanSelector(double mass) { + this.mass = new Mass(mass); + } + + @Override + public boolean test(Creature t) { + return t.getMass().greaterThan(mass); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java new file mode 100644 index 000000000000..94ab3cc9a1a8 --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/MassSmallerThanOrEqSelector.java @@ -0,0 +1,47 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Mass; + +/** + * Mass selector for values smaller or equal to the parameter. + */ +public class MassSmallerThanOrEqSelector extends AbstractSelector { + + private final Mass mass; + + /** + * The use of a double as a parameter will spare some typing when instantiating this class. + */ + public MassSmallerThanOrEqSelector(double mass) { + this.mass = new Mass(mass); + } + + @Override + public boolean test(Creature t) { + return t.getMass().smallerThanOrEq(mass); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java index 1818058c15d8..e2a0bdb15fad 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java @@ -25,12 +25,11 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; -import java.util.function.Predicate; /** * Movement selector. */ -public class MovementSelector implements Predicate { +public class MovementSelector extends AbstractSelector { private final Movement movement; diff --git a/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java new file mode 100644 index 000000000000..ad3063000845 --- /dev/null +++ b/specification/src/main/java/com/iluwatar/specification/selector/NegationSelector.java @@ -0,0 +1,46 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + + +/** + * A Selector defined as the negation (NOT) of a (leaf) selectors. This is of course only useful + * when used in combination with other composite selectors. + */ +public class NegationSelector extends AbstractSelector { + + private AbstractSelector component; + + NegationSelector(AbstractSelector selector) { + this.component = selector; + } + + /** + * Tests if the selector fails the test (yes). + */ + @Override + public boolean test(T t) { + return !(component.test(t)); + } +} diff --git a/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java b/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java index a997c034239d..6d5aa85d0bfe 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java @@ -25,12 +25,11 @@ import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; -import java.util.function.Predicate; /** * Size selector. */ -public class SizeSelector implements Predicate { +public class SizeSelector extends AbstractSelector { private final Size size; diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java index 5f6d950fe6f4..7585a113d34d 100644 --- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java +++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.Test; /** - * * Application test - * */ public class AppTest { diff --git a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java index 26ff4c1ab877..58af7248a867 100644 --- a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java +++ b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -23,17 +23,17 @@ package com.iluwatar.specification.creature; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Mass; import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.property.Size; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - import java.util.Collection; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Date: 12/29/15 - 7:47 PM @@ -47,12 +47,18 @@ public class CreatureTest { */ public static Collection dataProvider() { return List.of( - new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED}, - new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN}, - new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT}, - new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK}, - new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT}, - new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK} + new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED, + new Mass(39300.0)}, + new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN, + new Mass(30.0)}, + new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT, + new Mass(6.7)}, + new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK, + new Mass(12.0)}, + new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT, + new Mass(500.0)}, + new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK, + new Mass(4000.0)} ); } @@ -76,18 +82,28 @@ public void testGetMovement(Creature testedCreature, String name, Size size, Mov @ParameterizedTest @MethodSource("dataProvider") - public void testGetColor(Creature testedCreature, String name, Size size, Movement movement, Color color) { + public void testGetColor(Creature testedCreature, String name, Size size, Movement movement, + Color color) { assertEquals(color, testedCreature.getColor()); } @ParameterizedTest @MethodSource("dataProvider") - public void testToString(Creature testedCreature, String name, Size size, Movement movement, Color color) { + public void testGetMass(Creature testedCreature, String name, Size size, Movement movement, + Color color, Mass mass) { + assertEquals(mass, testedCreature.getMass()); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testToString(Creature testedCreature, String name, Size size, Movement movement, + Color color, Mass mass) { final String toString = testedCreature.toString(); assertNotNull(toString); assertEquals( - String.format("%s [size=%s, movement=%s, color=%s]", name, size, movement, color), - toString + String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, + mass), + toString ); } } \ No newline at end of file diff --git a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java index cc47ba5955e2..f1029063dc50 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -23,15 +23,15 @@ package com.iluwatar.specification.selector; -import com.iluwatar.specification.creature.Creature; -import com.iluwatar.specification.property.Color; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Color; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 7:35 PM * diff --git a/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java new file mode 100644 index 000000000000..75809c54280f --- /dev/null +++ b/specification/src/test/java/com/iluwatar/specification/selector/CompositeSelectorsTest.java @@ -0,0 +1,93 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Mass; +import com.iluwatar.specification.property.Movement; +import org.junit.jupiter.api.Test; + +public class CompositeSelectorsTest { + + /** + * Verify if the conjunction selector gives the correct results. + */ + @Test + public void testAndComposition() { + final Creature swimmingHeavyCreature = mock(Creature.class); + when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); + + final Creature swimmingLightCreature = mock(Creature.class); + when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); + + final AbstractSelector lightAndSwimmingSelector = new MassSmallerThanOrEqSelector( + 50.0).and(new MovementSelector(Movement.SWIMMING)); + assertFalse(lightAndSwimmingSelector.test(swimmingHeavyCreature)); + assertTrue(lightAndSwimmingSelector.test(swimmingLightCreature)); + } + + /** + * Verify if the disjunction selector gives the correct results. + */ + @Test + public void testOrComposition() { + final Creature swimmingHeavyCreature = mock(Creature.class); + when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); + + final Creature swimmingLightCreature = mock(Creature.class); + when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); + + final AbstractSelector lightOrSwimmingSelector = new MassSmallerThanOrEqSelector(50.0) + .or(new MovementSelector(Movement.SWIMMING)); + assertTrue(lightOrSwimmingSelector.test(swimmingHeavyCreature)); + assertTrue(lightOrSwimmingSelector.test(swimmingLightCreature)); + } + + /** + * Verify if the negation selector gives the correct results. + */ + @Test + public void testNotComposition() { + final Creature swimmingHeavyCreature = mock(Creature.class); + when(swimmingHeavyCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingHeavyCreature.getMass()).thenReturn(new Mass(100.0)); + + final Creature swimmingLightCreature = mock(Creature.class); + when(swimmingLightCreature.getMovement()).thenReturn(Movement.SWIMMING); + when(swimmingLightCreature.getMass()).thenReturn(new Mass(25.0)); + + final AbstractSelector heavySelector = new MassSmallerThanOrEqSelector(50.0).not(); + assertTrue(heavySelector.test(swimmingHeavyCreature)); + assertFalse(heavySelector.test(swimmingLightCreature)); + } +} diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java new file mode 100644 index 000000000000..287f401648e6 --- /dev/null +++ b/specification/src/test/java/com/iluwatar/specification/selector/MassSelectorTest.java @@ -0,0 +1,52 @@ +/* + * The MIT License + * Copyright © 2014-2019 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.specification.selector; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Mass; +import org.junit.jupiter.api.Test; + +public class MassSelectorTest { + + /** + * Verify if the mass selector gives the correct results. + */ + @Test + public void testMass() { + final Creature lightCreature = mock(Creature.class); + when(lightCreature.getMass()).thenReturn(new Mass(50.0)); + + final Creature heavyCreature = mock(Creature.class); + when(heavyCreature.getMass()).thenReturn(new Mass(2500.0)); + + final MassSmallerThanOrEqSelector lightSelector = new MassSmallerThanOrEqSelector(500.0); + assertTrue(lightSelector.test(lightCreature)); + assertFalse(lightSelector.test(heavyCreature)); + } +} diff --git a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java index e194790fbc2c..f3d2482ad9fc 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -23,15 +23,15 @@ package com.iluwatar.specification.selector; -import com.iluwatar.specification.creature.Creature; -import com.iluwatar.specification.property.Movement; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Movement; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 7:37 PM * @@ -40,7 +40,7 @@ public class MovementSelectorTest { /** - * Verify if the movement selector gives the correct results + * Verify if the movement selector gives the correct results. */ @Test public void testMovement() { diff --git a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java index 9145f9b810c6..7dcb30ee22f9 100644 --- a/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java +++ b/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -23,15 +23,15 @@ package com.iluwatar.specification.selector; -import com.iluwatar.specification.creature.Creature; -import com.iluwatar.specification.property.Size; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Size; +import org.junit.jupiter.api.Test; + /** * Date: 12/29/15 - 7:43 PM * diff --git a/state/pom.xml b/state/pom.xml index ac31bc5ebfa7..cb90a53f856a 100644 --- a/state/pom.xml +++ b/state/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT state diff --git a/step-builder/pom.xml b/step-builder/pom.xml index 23d73ed1b4a3..7733af66dfc9 100644 --- a/step-builder/pom.xml +++ b/step-builder/pom.xml @@ -30,7 +30,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT step-builder diff --git a/strategy/pom.xml b/strategy/pom.xml index d251b9a96610..a0f09297ecf2 100644 --- a/strategy/pom.xml +++ b/strategy/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT strategy diff --git a/subclass-sandbox/README.md b/subclass-sandbox/README.md index 674991f0895c..b4c8952b0507 100644 --- a/subclass-sandbox/README.md +++ b/subclass-sandbox/README.md @@ -1,4 +1,3 @@ - --- layout: pattern title: Subclass Sandbox @@ -9,7 +8,7 @@ tags: - Java - Difficulty-Beginner --- - + ## Intent The subclass sandbox pattern describes a basic idea, while not having a lot of detailed mechanics. You will need the pattern when you have several similar subclasses. If you have to make a tiny change, then change the base class, while all subclasses shouldn't have to be touched. So the base class has to be able to provide all of the operations a derived class needs to perform. diff --git a/subclass-sandbox/pom.xml b/subclass-sandbox/pom.xml index eb493b28cc3b..264343b00516 100644 --- a/subclass-sandbox/pom.xml +++ b/subclass-sandbox/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/template-method/pom.xml b/template-method/pom.xml index 0f4a03a5fec2..e236c28c8340 100644 --- a/template-method/pom.xml +++ b/template-method/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT template-method diff --git a/thread-pool/pom.xml b/thread-pool/pom.xml index 8968b3f4e70e..14946b393710 100644 --- a/thread-pool/pom.xml +++ b/thread-pool/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT thread-pool diff --git a/throttling/pom.xml b/throttling/pom.xml index 55e1b3e57ee8..5192ba28abb7 100644 --- a/throttling/pom.xml +++ b/throttling/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/tls/pom.xml b/tls/pom.xml index 050604d7bc50..48273ca715fd 100644 --- a/tls/pom.xml +++ b/tls/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT tls diff --git a/tolerant-reader/pom.xml b/tolerant-reader/pom.xml index e0d935112aaa..c0ebaeaec7e6 100644 --- a/tolerant-reader/pom.xml +++ b/tolerant-reader/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT tolerant-reader diff --git a/trampoline/README.md b/trampoline/README.md index cae343a61df9..dc0bb270cb78 100644 --- a/trampoline/README.md +++ b/trampoline/README.md @@ -3,7 +3,7 @@ layout: pattern title: Trampoline folder: trampoline permalink: /patterns/trampoline/ -categories: Behavior +categories: Behavioral tags: - Java - Difficulty-Intermediate diff --git a/trampoline/pom.xml b/trampoline/pom.xml index 99ef231ef534..1129de4fb265 100644 --- a/trampoline/pom.xml +++ b/trampoline/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT trampoline diff --git a/twin/pom.xml b/twin/pom.xml index 9e62469b15cb..bdde082d229f 100644 --- a/twin/pom.xml +++ b/twin/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT twin diff --git a/typeobjectpattern/pom.xml b/typeobjectpattern/pom.xml index 03d21de3770d..0d56a8376fdb 100644 --- a/typeobjectpattern/pom.xml +++ b/typeobjectpattern/pom.xml @@ -27,7 +27,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT typeobjectpattern diff --git a/unit-of-work/pom.xml b/unit-of-work/pom.xml index c27a674660aa..a92cc4110100 100644 --- a/unit-of-work/pom.xml +++ b/unit-of-work/pom.xml @@ -29,7 +29,7 @@ java-design-patterns com.iluwatar - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT 4.0.0 diff --git a/value-object/pom.xml b/value-object/pom.xml index 8aec02a8dfbe..bf8e4a1e2696 100644 --- a/value-object/pom.xml +++ b/value-object/pom.xml @@ -30,7 +30,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT value-object diff --git a/visitor/pom.xml b/visitor/pom.xml index c2a673ec6e4e..c7097611fde5 100644 --- a/visitor/pom.xml +++ b/visitor/pom.xml @@ -29,7 +29,7 @@ com.iluwatar java-design-patterns - 1.22.0-SNAPSHOT + 1.23.0-SNAPSHOT visitor