diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000000..0155bcdcd2b3 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [iluwatar] diff --git a/.travis.yml b/.travis.yml index bfb6d8422e29..0a5ac7709f2a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,8 +6,7 @@ sudo: required env: global: - - GH_REF: github.com/iluwatar/java-design-patterns.git - - secure: LxTDuNS/rBWIvKkaEqr79ImZAe48mCdoYCF41coxNXgNoippo4GIBArknqtv+XvdkiuRZ1yGyj6pn8GU33c/yn+krddTUkVCwTbVatbalW5jhQjDbHYym/JcxaK9ZS/3JTeGcWrBgiPqHEEDhCf26vPZsXoMSeVCEORVKTp1BSg= + - secure: "DCpazS3nkLnter3sguXEAS2fC/1ZWNfM+XLyif9MfNFxlZdpni2vCD/jA0Rdpga8puQWHNVLyAec+RPFH/2qSmJ1c1UTV5MaLv8tPqwUX0VFA+1I6XoSv6oX4ldHTBWHEWqQHkRFOLoil0h0edc0tTOWQwXF8U+DLAB+HkRb4gw=" services: - xvfb @@ -24,7 +23,7 @@ script: - 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then mvn clean verify sonar:sonar -Dsonar.projectKey=iluwatar_java-design-patterns -Dsonar.host.url=https://sonarcloud.io; fi' after_success: -- bash update-ghpages.sh +- bash update-website.sh notifications: email: diff --git a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java index a0d9d13c8a79..99be4ee12719 100644 --- a/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java +++ b/abstract-document/src/main/java/com/iluwatar/abstractdocument/App.java @@ -23,14 +23,13 @@ package com.iluwatar.abstractdocument; -import java.util.Arrays; -import java.util.HashMap; - +import com.iluwatar.abstractdocument.domain.Car; +import com.iluwatar.abstractdocument.domain.enums.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.iluwatar.abstractdocument.domain.Car; -import com.iluwatar.abstractdocument.domain.enums.Property; +import java.util.List; +import java.util.Map; /** * The Abstract Document pattern enables handling additional, non-static @@ -52,21 +51,20 @@ public class App { public App() { LOGGER.info("Constructing parts and car"); - var carProperties = new HashMap(); - carProperties.put(Property.MODEL.toString(), "300SL"); - carProperties.put(Property.PRICE.toString(), 10000L); - - var wheelProperties = new HashMap(); - wheelProperties.put(Property.TYPE.toString(), "wheel"); - wheelProperties.put(Property.MODEL.toString(), "15C"); - wheelProperties.put(Property.PRICE.toString(), 100L); + var wheelProperties = Map.of( + Property.TYPE.toString(), "wheel", + Property.MODEL.toString(), "15C", + Property.PRICE.toString(), 100L); - var doorProperties = new HashMap(); - doorProperties.put(Property.TYPE.toString(), "door"); - doorProperties.put(Property.MODEL.toString(), "Lambo"); - doorProperties.put(Property.PRICE.toString(), 300L); + var doorProperties = Map.of( + Property.TYPE.toString(), "door", + Property.MODEL.toString(), "Lambo", + Property.PRICE.toString(), 300L); - carProperties.put(Property.PARTS.toString(), Arrays.asList(wheelProperties, doorProperties)); + var carProperties = Map.of( + Property.MODEL.toString(), "300SL", + Property.PRICE.toString(), 10000L, + Property.PARTS.toString(), List.of(wheelProperties, doorProperties)); var car = new Car(carProperties); diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java index 7f3e1eada124..da576539102a 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -25,15 +25,12 @@ import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * AbstractDocument test class @@ -60,9 +57,7 @@ public void shouldPutAndGetValue() { @Test public void shouldRetrieveChildren() { - Map child1 = new HashMap<>(); - Map child2 = new HashMap<>(); - List> children = Arrays.asList(child1, child2); + var children = List.of(Map.of(), Map.of()); document.put(KEY, children); @@ -80,8 +75,7 @@ public void shouldRetrieveEmptyStreamForNonExistingChildren() { @Test public void shouldIncludePropsInToString() { - Map props = new HashMap<>(); - props.put(KEY, VALUE); + Map props = Map.of(KEY, VALUE); DocumentImplementation document = new DocumentImplementation(props); assertTrue(document.toString().contains(KEY)); assertTrue(document.toString().contains(VALUE)); diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java index 2dde49a1ea2a..eed4ad9bb94e 100644 --- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java +++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -23,17 +23,15 @@ package com.iluwatar.abstractdocument; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; - import com.iluwatar.abstractdocument.domain.Car; import com.iluwatar.abstractdocument.domain.Part; import com.iluwatar.abstractdocument.domain.enums.Property; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Part and Car @@ -49,10 +47,10 @@ public class DomainTest { @Test public void shouldConstructPart() { - Map partProperties = new HashMap<>(); - partProperties.put(Property.TYPE.toString(), TEST_PART_TYPE); - partProperties.put(Property.MODEL.toString(), TEST_PART_MODEL); - partProperties.put(Property.PRICE.toString(), TEST_PART_PRICE); + Map partProperties = Map.of( + Property.TYPE.toString(), TEST_PART_TYPE, + Property.MODEL.toString(), TEST_PART_MODEL, + Property.PRICE.toString(), TEST_PART_PRICE); Part part = new Part(partProperties); assertEquals(TEST_PART_TYPE, part.getType().get()); @@ -62,10 +60,10 @@ public void shouldConstructPart() { @Test public void shouldConstructCar() { - Map carProperties = new HashMap<>(); - carProperties.put(Property.MODEL.toString(), TEST_CAR_MODEL); - carProperties.put(Property.PRICE.toString(), TEST_CAR_PRICE); - carProperties.put(Property.PARTS.toString(), Arrays.asList(new HashMap<>(), new HashMap<>())); + Map carProperties = Map.of( + Property.MODEL.toString(), TEST_CAR_MODEL, + Property.PRICE.toString(), TEST_CAR_PRICE, + Property.PARTS.toString(), List.of(Map.of(), Map.of())); Car car = new Car(carProperties); assertEquals(TEST_CAR_MODEL, car.getModel().get()); diff --git a/abstract-factory/README.md b/abstract-factory/README.md index 0084030b645e..aefedb07f7f4 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -188,10 +188,6 @@ Use the Abstract Factory pattern when ## Tutorial * [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java) -## Presentations - -* [Abstract Factory Pattern](etc/presentation.html) - ## Real world examples diff --git a/abstract-factory/etc/diagram1.png b/abstract-factory/etc/diagram1.png deleted file mode 100644 index e9c3c84c212d..000000000000 Binary files a/abstract-factory/etc/diagram1.png and /dev/null differ diff --git a/abstract-factory/etc/diagram2.png b/abstract-factory/etc/diagram2.png deleted file mode 100644 index 2ab52453533f..000000000000 Binary files a/abstract-factory/etc/diagram2.png and /dev/null differ diff --git a/abstract-factory/etc/presentation.html b/abstract-factory/etc/presentation.html deleted file mode 100644 index 823245870569..000000000000 --- a/abstract-factory/etc/presentation.html +++ /dev/null @@ -1,190 +0,0 @@ - - - - - Design Patterns - Abstract Factory Presentation - - - - - - - - - \ No newline at end of file diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/adapter/App.java index a3bf5b14b35c..570cc8272e44 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/adapter/App.java @@ -24,37 +24,44 @@ package com.iluwatar.adapter; /** - * An adapter helps two incompatible interfaces to work together. This is the real world definition - * for an adapter. Interfaces may be incompatible but the inner functionality should suit the need. - * The Adapter design pattern allows otherwise incompatible classes to work together by converting - * the interface of one class into an interface expected by the clients. + * An adapter helps two incompatible interfaces to work together. This is the + * real world definition for an adapter. Interfaces may be incompatible but + * the inner functionality should suit the need. The Adapter design pattern + * allows otherwise incompatible classes to work together by converting the + * interface of one class into an interface expected by the clients. * *

- * There are two variations of the Adapter pattern: The class adapter implements the adaptee's - * interface whereas the object adapter uses composition to contain the adaptee in the adapter - * object. This example uses the object adapter approach. + * There are two variations of the Adapter pattern: The class adapter + * implements the adaptee's interface whereas the object adapter uses + * composition to contain the adaptee in the adapter object. This example uses + * the object adapter approach. * *

- * The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class ( - * {@link FishingBoat}) into a suitable one expected by the client ( {@link RowingBoat} ). + * The Adapter ({@link FishingBoatAdapter}) converts the interface of the + * adaptee class ({@link FishingBoat}) into a suitable one expected by the + * client ({@link RowingBoat}). * *

* The story of this implementation is this.
- * Pirates are coming! we need a {@link RowingBoat} to flee! We have a {@link FishingBoat} and our - * captain. We have no time to make up a new ship! we need to reuse this {@link FishingBoat}. The - * captain needs a rowing boat which he can operate. The spec is in {@link RowingBoat}. We will - * use the Adapter pattern to reuse {@link FishingBoat}. + * Pirates are coming! we need a {@link RowingBoat} to flee! We have a + * {@link FishingBoat} and our captain. We have no time to make up a new ship! + * we need to reuse this {@link FishingBoat}. The captain needs a rowing boat + * which he can operate. The spec is in {@link RowingBoat}. We will use the + * Adapter pattern to reuse {@link FishingBoat}. * */ -public class App { +public final class App { + + private App() { } /** * Program entry point. * * @param args command line args */ - public static void main(String[] args) { - // The captain can only operate rowing boats but with adapter he is able to use fishing boats as well + public static void main(final String[] args) { + // The captain can only operate rowing boats but with adapter he is able to + // use fishing boats as well var captain = new Captain(new FishingBoatAdapter()); captain.row(); } diff --git a/adapter/src/main/java/com/iluwatar/adapter/Captain.java b/adapter/src/main/java/com/iluwatar/adapter/Captain.java index fbf0be6ca628..1eb3aaa1aba3 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/Captain.java +++ b/adapter/src/main/java/com/iluwatar/adapter/Captain.java @@ -27,21 +27,21 @@ * The Captain uses {@link RowingBoat} to sail.
* This is the client in the pattern. */ -public class Captain { +public final class Captain { private RowingBoat rowingBoat; - public Captain() {} + public Captain() { } - public Captain(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; + public Captain(final RowingBoat boat) { + this.rowingBoat = boat; } - public void setRowingBoat(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; + void setRowingBoat(final RowingBoat boat) { + this.rowingBoat = boat; } - public void row() { + void row() { rowingBoat.row(); } diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java index 6c2daae3d2df..1dbf5eed34bf 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java @@ -24,7 +24,8 @@ package com.iluwatar.adapter; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.slf4j.LoggerFactory.getLogger; /** * @@ -32,11 +33,11 @@ * Fishing boat moves by sailing. * */ -public class FishingBoat { +final class FishingBoat { - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); + private static final Logger LOGGER = getLogger(FishingBoat.class); - public void sail() { + void sail() { LOGGER.info("The fishing boat is sailing"); } diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java index 7dda379c9271..7aaacd3e575b 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java @@ -25,8 +25,8 @@ /** * - * Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link RowingBoat} - * interface expected by the client ({@link Captain}). + * Adapter class. Adapts the interface of the device ({@link FishingBoat}) + * into {@link RowingBoat} interface expected by the client ({@link Captain}). * */ public class FishingBoatAdapter implements RowingBoat { @@ -37,8 +37,7 @@ public FishingBoatAdapter() { boat = new FishingBoat(); } - @Override - public void row() { + public final void row() { boat.sail(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/package-info.java b/adapter/src/main/java/com/iluwatar/adapter/package-info.java new file mode 100644 index 000000000000..d036d86ddb47 --- /dev/null +++ b/adapter/src/main/java/com/iluwatar/adapter/package-info.java @@ -0,0 +1,24 @@ +/* + * 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.adapter; diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java index e96ac9d43c2c..dbed50fc6610 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/Aggregator.java @@ -51,9 +51,23 @@ public class Aggregator { */ @RequestMapping(path = "/product", method = RequestMethod.GET) public Product getProduct() { + var product = new Product(); - product.setTitle(informationClient.getProductTitle()); - product.setProductInventories(inventoryClient.getProductInventories()); + String productTitle = informationClient.getProductTitle(); + Integer productInventory = inventoryClient.getProductInventories(); + + if (productTitle != null) { + product.setTitle(productTitle); + } else { + product.setTitle("Error: Fetching Product Title Failed"); //Fallback to error message + } + + if (productInventory != null) { + product.setProductInventories(productInventory); + } else { + product.setProductInventories(-1); //Fallback to default error inventory + } + return product; } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java index ed325be0070f..22369350a203 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClient.java @@ -28,5 +28,5 @@ */ public interface ProductInventoryClient { - int getProductInventories(); + Integer getProductInventories(); } diff --git a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java index c43fe84c61ca..fcd824de7aca 100644 --- a/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java +++ b/aggregator-microservices/aggregator-service/src/main/java/com/iluwatar/aggregator/microservices/ProductInventoryClientImpl.java @@ -42,8 +42,8 @@ public class ProductInventoryClientImpl implements ProductInventoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(ProductInventoryClientImpl.class); @Override - public int getProductInventories() { - var response = "0"; + public Integer getProductInventories() { + var response = ""; var request = HttpRequest.newBuilder().GET().uri(URI.create("http://localhost:51516/inventories")).build(); var client = HttpClient.newHttpClient(); @@ -55,6 +55,10 @@ public int getProductInventories() { } catch (InterruptedException ie) { LOGGER.error("InterruptedException Occurred", ie); } - return Integer.parseInt(response); + if("".equalsIgnoreCase(response)) { + return null; + } else { + return Integer.parseInt(response); + } } } diff --git a/callback/src/main/java/com/iluwatar/callback/App.java b/callback/src/main/java/com/iluwatar/callback/App.java index 3a9cd00cb185..842f01dcdf3d 100644 --- a/callback/src/main/java/com/iluwatar/callback/App.java +++ b/callback/src/main/java/com/iluwatar/callback/App.java @@ -24,23 +24,27 @@ package com.iluwatar.callback; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.slf4j.LoggerFactory.getLogger; /** - * - * Callback pattern is more native for functional languages where functions are treated as - * first-class citizens. Prior to Java 8 callbacks can be simulated using simple (alike command) - * interfaces. - * + * + * Callback pattern is more native for functional languages where functions are + * treated as first-class citizens. Prior to Java 8 callbacks can be simulated + * using simple (alike command) interfaces. + * */ -public class App { +public final class App { - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + private static final Logger LOGGER = getLogger(App.class); + + private App() { + } /** * Program entry point */ - public static void main(String[] args) { + public static void main(final String[] args) { Task task = new SimpleTask(); Callback callback = () -> LOGGER.info("I'm done now."); task.executeWith(callback); diff --git a/callback/src/main/java/com/iluwatar/callback/Callback.java b/callback/src/main/java/com/iluwatar/callback/Callback.java index 15f08366275d..0158dcda0fe6 100644 --- a/callback/src/main/java/com/iluwatar/callback/Callback.java +++ b/callback/src/main/java/com/iluwatar/callback/Callback.java @@ -24,9 +24,9 @@ package com.iluwatar.callback; /** - * + * * Callback interface - * + * */ public interface Callback { diff --git a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java index 2b445d9ca440..18715e3b79ca 100644 --- a/callback/src/main/java/com/iluwatar/callback/LambdasApp.java +++ b/callback/src/main/java/com/iluwatar/callback/LambdasApp.java @@ -24,22 +24,25 @@ package com.iluwatar.callback; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.slf4j.LoggerFactory.getLogger; /** * - * This example generates the exact same output as {@link App} however the callback has been - * defined as a Lambdas expression. + * This example generates the exact same output as {@link App} however the + * callback has been defined as a Lambdas expression. * */ -public class LambdasApp { +public final class LambdasApp { + + private static final Logger LOGGER = getLogger(LambdasApp.class); - private static final Logger LOGGER = LoggerFactory.getLogger(LambdasApp.class); + private LambdasApp() { } /** * Program entry point */ - public static void main(String[] args) { + public static void main(final String[] args) { Task task = new SimpleTask(); Callback c = () -> LOGGER.info("I'm done now."); task.executeWith(c); diff --git a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java index 155d1e96dad7..21162833a72c 100644 --- a/callback/src/main/java/com/iluwatar/callback/SimpleTask.java +++ b/callback/src/main/java/com/iluwatar/callback/SimpleTask.java @@ -24,19 +24,21 @@ package com.iluwatar.callback; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.slf4j.LoggerFactory.getLogger; /** - * + * * Implementation of task that need to be executed - * + * */ -public class SimpleTask extends Task { +public final class SimpleTask extends Task { - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTask.class); + private static final Logger LOGGER = getLogger(SimpleTask.class); @Override public void execute() { - LOGGER.info("Perform some important activity and after call the callback method."); + LOGGER.info("Perform some important activity and after call the" + + " callback method."); } } diff --git a/callback/src/main/java/com/iluwatar/callback/Task.java b/callback/src/main/java/com/iluwatar/callback/Task.java index 9f2abe85fa21..15cd99e9ae70 100644 --- a/callback/src/main/java/com/iluwatar/callback/Task.java +++ b/callback/src/main/java/com/iluwatar/callback/Task.java @@ -24,16 +24,16 @@ package com.iluwatar.callback; /** - * + * * Template-method class for callback hook execution - * + * */ public abstract class Task { /** * Execute with callback */ - public final void executeWith(Callback callback) { + final void executeWith(final Callback callback) { execute(); if (callback != null) { callback.call(); diff --git a/callback/src/main/java/com/iluwatar/callback/package-info.java b/callback/src/main/java/com/iluwatar/callback/package-info.java new file mode 100644 index 000000000000..0b86125fd678 --- /dev/null +++ b/callback/src/main/java/com/iluwatar/callback/package-info.java @@ -0,0 +1,24 @@ +/* + * 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.callback; diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java index 3a811f0e0806..de19a3b15508 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/App.java @@ -23,13 +23,12 @@ package com.iluwatar.collectionpipeline; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.Map; + /** * In imperative-style programming, it is common to use for and while loops for * most kinds of data processing. Function composition is a simple technique @@ -67,11 +66,11 @@ public static void main(String[] args) { LOGGER.info(groupingByCategoryFunctional.toString()); Person john = new Person(cars); - - List sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + + List sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedImperative.toString()); - List sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + List sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); LOGGER.info(sedansOwnedFunctional.toString()); } } diff --git a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java index 6e4531f5fb0a..aee1e21932df 100644 --- a/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java +++ b/collection-pipeline/src/main/java/com/iluwatar/collectionpipeline/CarFactory.java @@ -23,7 +23,6 @@ package com.iluwatar.collectionpipeline; -import java.util.Arrays; import java.util.List; /** @@ -38,7 +37,7 @@ private CarFactory() { * @return {@link List} of {@link Car} */ public static List createCars() { - return Arrays.asList(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + return List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), new Car("Jeep", "Comanche", 1990, Category.JEEP), new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), diff --git a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java index 5cec263cdead..6bc035920d88 100644 --- a/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java +++ b/collection-pipeline/src/test/java/com/iluwatar/collectionpipeline/AppTest.java @@ -23,16 +23,14 @@ package com.iluwatar.collectionpipeline; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests that Collection Pipeline methods work as expected. @@ -44,27 +42,27 @@ public class AppTest { @Test public void testGetModelsAfter2000UsingFor() { - List models = ImperativeProgramming.getModelsAfter2000(cars); - assertEquals(Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada"), models); + var models = ImperativeProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } @Test public void testGetModelsAfter2000UsingPipeline() { - List models = FunctionalProgramming.getModelsAfter2000(cars); - assertEquals(Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada"), models); + var models = FunctionalProgramming.getModelsAfter2000(cars); + assertEquals(List.of("Avenger", "Wrangler", "Focus", "Cascada"), models); } @Test public void testGetGroupingOfCarsByCategory() { - Map> modelsExpected = new HashMap<>(); - modelsExpected.put(Category.CONVERTIBLE, Arrays.asList(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), - new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE))); - modelsExpected.put(Category.SEDAN, Arrays.asList(new Car("Dodge", "Avenger", 2010, Category.SEDAN), - new Car("Ford", "Focus", 2012, Category.SEDAN))); - modelsExpected.put(Category.JEEP, Arrays.asList(new Car("Jeep", "Wrangler", 2011, Category.JEEP), - new Car("Jeep", "Comanche", 1990, Category.JEEP))); - Map> modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); - Map> modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); + var modelsExpected = Map.of( + Category.CONVERTIBLE, List.of(new Car("Buick", "Cascada", 2016, Category.CONVERTIBLE), + new Car("Chevrolet", "Geo Metro", 1992, Category.CONVERTIBLE)), + Category.SEDAN, List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), + new Car("Ford", "Focus", 2012, Category.SEDAN)), + Category.JEEP, List.of(new Car("Jeep", "Wrangler", 2011, Category.JEEP), + new Car("Jeep", "Comanche", 1990, Category.JEEP))); + var modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); + var modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info("Category " + modelsFunctional); assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsImperative); @@ -72,11 +70,11 @@ public void testGetGroupingOfCarsByCategory() { @Test public void testGetSedanCarsOwnedSortedByDate() { - Person john = new Person(cars); - List modelsExpected = Arrays.asList(new Car("Dodge", "Avenger", 2010, Category.SEDAN), + var john = new Person(cars); + var modelsExpected = List.of(new Car("Dodge", "Avenger", 2010, Category.SEDAN), new Car("Ford", "Focus", 2012, Category.SEDAN)); - List modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); - List modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); + var modelsFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); + var modelsImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(List.of(john)); assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsImperative); } diff --git a/command/README.md b/command/README.md index cb9bd48a9608..41e8b78e1aaa 100644 --- a/command/README.md +++ b/command/README.md @@ -36,10 +36,6 @@ Use the Command pattern when you want to * implement callback functionality * implement the undo functionality -## Presentations - -* [Command Pattern](etc/presentation.html) - ## Real world examples * [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) diff --git a/command/etc/diagram.png b/command/etc/diagram.png deleted file mode 100644 index 1d3494292b82..000000000000 Binary files a/command/etc/diagram.png and /dev/null differ diff --git a/command/etc/presentation.html b/command/etc/presentation.html deleted file mode 100644 index f6db44f5b5de..000000000000 --- a/command/etc/presentation.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - Design Patterns - Command Presentation - - - - - - - - - \ No newline at end of file diff --git a/commander/src/main/java/com/iluwatar/commander/Service.java b/commander/src/main/java/com/iluwatar/commander/Service.java index f3b1940c7093..64af79053459 100644 --- a/commander/src/main/java/com/iluwatar/commander/Service.java +++ b/commander/src/main/java/com/iluwatar/commander/Service.java @@ -23,10 +23,8 @@ package com.iluwatar.commander; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.Random; +import java.util.*; + import com.iluwatar.commander.exceptions.DatabaseUnavailableException; /** @@ -45,11 +43,11 @@ public abstract class Service { public ArrayList exceptionsList; private static final Random RANDOM = new Random(); private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - private static final Hashtable USED_IDS = new Hashtable(); + private static final Hashtable USED_IDS = new Hashtable<>(); protected Service(Database db, Exception...exc) { this.database = db; - this.exceptionsList = new ArrayList(Arrays.asList(exc)); + this.exceptionsList = new ArrayList<>(List.of(exc)); } public abstract String receiveRequest(Object...parameters) throws DatabaseUnavailableException; diff --git a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java index 0010ce1f4d3e..6b9007b9fd36 100644 --- a/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java +++ b/commander/src/main/java/com/iluwatar/commander/queue/QueueDatabase.java @@ -23,12 +23,13 @@ package com.iluwatar.commander.queue; -import java.util.ArrayList; -import java.util.Arrays; import com.iluwatar.commander.Database; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.IsEmptyException; +import java.util.ArrayList; +import java.util.List; + /** * QueueDatabase id where the instructions to be implemented are queued. */ @@ -39,8 +40,8 @@ public class QueueDatabase extends Database { public ArrayList exceptionsList; public QueueDatabase(Exception...exc) { - this.data = new Queue(); - this.exceptionsList = new ArrayList(Arrays.asList(exc)); + this.data = new Queue<>(); + this.exceptionsList = new ArrayList<>(List.of(exc)); } @Override diff --git a/commander/src/test/java/com/iluwatar/commander/RetryTest.java b/commander/src/test/java/com/iluwatar/commander/RetryTest.java index 7dd142b9c83a..749b2619cbac 100644 --- a/commander/src/test/java/com/iluwatar/commander/RetryTest.java +++ b/commander/src/test/java/com/iluwatar/commander/RetryTest.java @@ -23,18 +23,14 @@ package com.iluwatar.commander; -import static org.junit.jupiter.api.Assertions.*; -import java.util.ArrayList; -import java.util.Arrays; -import org.junit.jupiter.api.Test; - -import com.iluwatar.commander.Order; -import com.iluwatar.commander.Retry; -import com.iluwatar.commander.User; -import com.iluwatar.commander.Retry.HandleErrorIssue; -import com.iluwatar.commander.Retry.Operation; import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.ItemUnavailableException; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; class RetryTest { @@ -49,21 +45,21 @@ void performTest() { Retry.HandleErrorIssue handleError = (o,e) -> { return; }; - Retry r1 = new Retry(op, handleError, 3, 30000, + Retry r1 = new Retry<>(op, handleError, 3, 30000, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); - Retry r2 = new Retry(op, handleError, 3, 30000, + Retry r2 = new Retry<>(op, handleError, 3, 30000, e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); User user = new User("Jim", "ABCD"); Order order = new Order(user, "book", 10f); - ArrayList arr1 = new ArrayList(Arrays.asList(new Exception[] - {new ItemUnavailableException(), new DatabaseUnavailableException()})); + ArrayList arr1 = new ArrayList<>(List.of( + new ItemUnavailableException(), new DatabaseUnavailableException())); try { r1.perform(arr1, order); } catch (Exception e1) { e1.printStackTrace(); } - ArrayList arr2 = new ArrayList(Arrays.asList(new Exception[] - {new DatabaseUnavailableException(), new ItemUnavailableException()})); + ArrayList arr2 = new ArrayList<>(List.of( + new DatabaseUnavailableException(), new ItemUnavailableException())); try { r2.perform(arr2, order); } catch (Exception e1) { diff --git a/composite/README.md b/composite/README.md index 05ee70cbb9b9..68d5339fb016 100644 --- a/composite/README.md +++ b/composite/README.md @@ -94,27 +94,27 @@ Then we have a messenger to carry messages ```java public class Messenger { LetterComposite messageFromOrcs() { - List words = new ArrayList<>(); - words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('a')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'), new Letter('i'), new Letter('p')))); - words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('a')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'), new Letter('y')))); + List words = List.of( + new Word(List.of(new Letter('W'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))), + new Word(List.of(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))), + new Word(List.of(new Letter('i'), new Letter('s'))), + new Word(List.of(new Letter('a'))), + new Word(List.of(new Letter('w'), new Letter('h'), new Letter('i'), new Letter('p'))), + new Word(List.of(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))), + new Word(List.of(new Letter('i'), new Letter('s'))), + new Word(List.of(new Letter('a'))), + new Word(List.of(new Letter('w'), new Letter('a'), new Letter('y')))); return new Sentence(words); } LetterComposite messageFromElves() { - List words = new ArrayList<>(); - words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'), new Letter('c'), new Letter('h')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d')))); - words.add(new Word(Arrays.asList(new Letter('p'), new Letter('o'), new Letter('u'), new Letter('r'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'), new Letter('o'), new Letter('m')))); - words.add(new Word(Arrays.asList(new Letter('y'), new Letter('o'), new Letter('u'), new Letter('r')))); - words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('t'), new Letter('h')))); + List words = List.of( + new Word(List.of(new Letter('M'), new Letter('u'), new Letter('c'), new Letter('h'))), + new Word(List.of(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d'))), + new Word(List.of(new Letter('p'), new Letter('o'), new Letter('u'), new Letter('r'), new Letter('s'))), + new Word(List.of(new Letter('f'), new Letter('r'), new Letter('o'), new Letter('m'))), + new Word(List.of(new Letter('y'), new Letter('o'), new Letter('u'), new Letter('r'))), + new Word(List.of(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('t'), new Letter('h')))); return new Sentence(words); } } diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java index eb55b7762c49..7389c7a960e3 100644 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ b/composite/src/main/java/com/iluwatar/composite/App.java @@ -32,9 +32,9 @@ * of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. * Implementing the Composite pattern lets clients treat individual objects and compositions * uniformly. - *

- * In this example we have sentences composed of words composed of letters. All of the objects can - * be treated through the same interface ({@link LetterComposite}). + * + *

In this example we have sentences composed of words composed of letters. All of the objects + * can be treated through the same interface ({@link LetterComposite}). * */ public class App { @@ -42,7 +42,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/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java index 4583f908985c..ab2d496ea871 100644 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ b/composite/src/main/java/com/iluwatar/composite/Letter.java @@ -24,20 +24,18 @@ package com.iluwatar.composite; /** - * - * Letter - * + * Letter. */ public class Letter extends LetterComposite { - private char c; + private char character; public Letter(char c) { - this.c = c; + this.character = c; } @Override protected void printThisBefore() { - System.out.print(c); + System.out.print(character); } } diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java index 673e28f7918c..5d8af5435a45 100644 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java @@ -27,9 +27,7 @@ import java.util.List; /** - * * Composite interface. - * */ public abstract class LetterComposite { @@ -43,12 +41,14 @@ public int count() { return children.size(); } - protected void printThisBefore() {} + protected void printThisBefore() { + } - protected void printThisAfter() {} + protected void printThisAfter() { + } /** - * Print + * Print. */ public void print() { printThisBefore(); diff --git a/composite/src/main/java/com/iluwatar/composite/Messenger.java b/composite/src/main/java/com/iluwatar/composite/Messenger.java index c4d99faf61fa..55929e7eebd3 100644 --- a/composite/src/main/java/com/iluwatar/composite/Messenger.java +++ b/composite/src/main/java/com/iluwatar/composite/Messenger.java @@ -23,34 +23,29 @@ package com.iluwatar.composite; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** - * - * Messenger - * + * Messenger. */ public class Messenger { LetterComposite messageFromOrcs() { - List words = new ArrayList<>(); - - words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'), new Letter('e'), new Letter( - 'r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter( - 'r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('a')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'), new Letter('i'), new Letter( - 'p')))); - words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter( - 'r'), new Letter('e')))); - words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('a')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'), new Letter('y')))); + List words = List.of( + new Word(List.of(new Letter('W'), new Letter('h'), new Letter('e'), new Letter( + 'r'), new Letter('e'))), + new Word(List.of(new Letter('t'), new Letter('h'), new Letter('e'), new Letter( + 'r'), new Letter('e'))), + new Word(List.of(new Letter('i'), new Letter('s'))), + new Word(List.of(new Letter('a'))), + new Word(List.of(new Letter('w'), new Letter('h'), new Letter('i'), new Letter( + 'p'))), + new Word(List.of(new Letter('t'), new Letter('h'), new Letter('e'), new Letter( + 'r'), new Letter('e'))), + new Word(List.of(new Letter('i'), new Letter('s'))), + new Word(List.of(new Letter('a'))), + new Word(List.of(new Letter('w'), new Letter('a'), new Letter('y')))); return new Sentence(words); @@ -58,20 +53,15 @@ LetterComposite messageFromOrcs() { LetterComposite messageFromElves() { - List words = new ArrayList<>(); - - words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'), new Letter('c'), new Letter( - 'h')))); - words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'), new Letter('n'), new Letter( - 'd')))); - words.add(new Word(Arrays.asList(new Letter('p'), new Letter('o'), new Letter('u'), new Letter( - 'r'), new Letter('s')))); - words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'), new Letter('o'), new Letter( - 'm')))); - words.add(new Word(Arrays.asList(new Letter('y'), new Letter('o'), new Letter('u'), new Letter( - 'r')))); - words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'), new Letter('u'), new Letter( - 't'), new Letter('h')))); + List words = List.of( + new Word(List.of(new Letter('M'), new Letter('u'), new Letter('c'), new Letter('h'))), + new Word(List.of(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d'))), + new Word(List.of(new Letter('p'), new Letter('o'), new Letter('u'), new Letter('r'), + new Letter('s'))), + new Word(List.of(new Letter('f'), new Letter('r'), new Letter('o'), new Letter('m'))), + new Word(List.of(new Letter('y'), new Letter('o'), new Letter('u'), new Letter('r'))), + new Word(List.of(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('t'), + new Letter('h')))); return new Sentence(words); diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index 08e12f1526d6..c94ce84aa767 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -26,14 +26,12 @@ import java.util.List; /** - * - * Sentence - * + * Sentence. */ public class Sentence extends LetterComposite { /** - * Constructor + * Constructor. */ public Sentence(List words) { for (Word w : words) { diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 7c71a7fddeec..353c363a287d 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -26,14 +26,12 @@ import java.util.List; /** - * - * Word - * + * Word. */ public class Word extends LetterComposite { /** - * Constructor + * Constructor. */ public Word(List letters) { for (Letter l : letters) { diff --git a/converter/src/main/java/com/iluwatar/converter/App.java b/converter/src/main/java/com/iluwatar/converter/App.java index 0d4666ae6cb2..fab472328afd 100644 --- a/converter/src/main/java/com/iluwatar/converter/App.java +++ b/converter/src/main/java/com/iluwatar/converter/App.java @@ -24,11 +24,9 @@ package com.iluwatar.converter; -import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.List; /** @@ -38,7 +36,7 @@ * objects between types. */ public class App { - + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point @@ -52,7 +50,7 @@ public static void main(String[] args) { User user = userConverter.convertFromDto(dtoUser); LOGGER.info("Entity converted from DTO:" + user); - ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), + var users = List.of(new User("Camile", "Tough", false, "124sad"), new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); LOGGER.info("Domain entities:"); users.stream().map(User::toString).forEach(LOGGER::info); diff --git a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java index 90160c4678df..92d47bb41087 100644 --- a/converter/src/test/java/com/iluwatar/converter/ConverterTest.java +++ b/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -23,10 +23,8 @@ package com.iluwatar.converter; -import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; -import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -81,8 +79,9 @@ public void testCustomConverter() { */ @Test public void testCollectionConversion() { - ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), - new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); + List users = List.of(new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), + new User("Kate", "Smith", true, "if0243")); List fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); assertEquals(users, fromDtos); } diff --git a/dao/src/main/java/com/iluwatar/dao/App.java b/dao/src/main/java/com/iluwatar/dao/App.java index c8dd5629db7a..78406208a77e 100644 --- a/dao/src/main/java/com/iluwatar/dao/App.java +++ b/dao/src/main/java/com/iluwatar/dao/App.java @@ -128,10 +128,6 @@ public static List generateSampleCustomers() { final Customer customer1 = new Customer(1, "Adam", "Adamson"); final Customer customer2 = new Customer(2, "Bob", "Bobson"); final Customer customer3 = new Customer(3, "Carl", "Carlson"); - final List customers = new ArrayList<>(); - customers.add(customer1); - customers.add(customer2); - customers.add(customer3); - return customers; + return List.of(customer1, customer2, customer3); } } diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java index 08d5440b9bc3..e6b670a6d524 100644 --- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java +++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java @@ -26,7 +26,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.List; /** @@ -59,11 +58,11 @@ public class App { */ public static void main(String[] args) { // initialize game objects and print their status - List objects = new ArrayList<>(); - objects.add(new FlamingAsteroid(0, 0, 5, 5)); - objects.add(new SpaceStationMir(1, 1, 2, 2)); - objects.add(new Meteoroid(10, 10, 15, 15)); - objects.add(new SpaceStationIss(12, 12, 14, 14)); + List objects = List.of( + new FlamingAsteroid(0, 0, 5, 5), + new SpaceStationMir(1, 1, 2, 2), + new Meteoroid(10, 10, 15, 15), + new SpaceStationIss(12, 12, 14, 14)); objects.stream().forEach(o -> LOGGER.info(o.toString())); LOGGER.info(""); diff --git a/facade/README.md b/facade/README.md index 505ceee394bb..d6c64500c3f8 100644 --- a/facade/README.md +++ b/facade/README.md @@ -146,10 +146,10 @@ public class DwarvenGoldmineFacade { private final List workers; public DwarvenGoldmineFacade() { - workers = new ArrayList<>(); - workers.add(new DwarvenGoldDigger()); - workers.add(new DwarvenCartOperator()); - workers.add(new DwarvenTunnelDigger()); + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); } public void startNewDay() { diff --git a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java index e7062f334617..b49d46e93b53 100644 --- a/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java +++ b/facade/src/main/java/com/iluwatar/facade/DwarvenGoldmineFacade.java @@ -23,7 +23,6 @@ package com.iluwatar.facade; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -43,10 +42,10 @@ public class DwarvenGoldmineFacade { * Constructor */ public DwarvenGoldmineFacade() { - workers = new ArrayList<>(); - workers.add(new DwarvenGoldDigger()); - workers.add(new DwarvenCartOperator()); - workers.add(new DwarvenTunnelDigger()); + workers = List.of( + new DwarvenGoldDigger(), + new DwarvenCartOperator(), + new DwarvenTunnelDigger()); } public void startNewDay() { diff --git a/factory-method/README.md b/factory-method/README.md index 087221fb9dfe..be5ead3e7329 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -42,13 +42,13 @@ public interface Blacksmith { public class ElfBlacksmith implements Blacksmith { public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); + return ELFARSENAL.get(weaponType); } } public class OrcBlacksmith implements Blacksmith { public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); + return ORCARSENAL.get(weaponType); } } ``` @@ -69,10 +69,6 @@ Use the Factory Method pattern when * a class wants its subclasses to specify the objects it creates * classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate -## Presentations - -* [Factory Method Pattern](etc/presentation.html) - ## Real world examples * [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) diff --git a/factory-method/etc/diagram1.png b/factory-method/etc/diagram1.png deleted file mode 100644 index fa325edf002a..000000000000 Binary files a/factory-method/etc/diagram1.png and /dev/null differ diff --git a/factory-method/etc/presentation.html b/factory-method/etc/presentation.html deleted file mode 100644 index df520605ad53..000000000000 --- a/factory-method/etc/presentation.html +++ /dev/null @@ -1,185 +0,0 @@ - - - - - Design Patterns - Factory Method Presentation - - - - - - - - - \ No newline at end of file diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/App.java b/factory-method/src/main/java/com/iluwatar/factory/method/App.java index 8c66b70d2549..8ebf54b03965 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/App.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/App.java @@ -27,14 +27,13 @@ import org.slf4j.LoggerFactory; /** - * * The Factory Method is a creational design pattern which uses factory methods to deal with the * problem of creating objects without specifying the exact class of object that will be created. * This is done by creating objects via calling a factory method either specified in an interface * and implemented by child classes, or implemented in a base class and optionally overridden by * derived classes—rather than by calling a constructor. - *

- * In this Factory Method example we have an interface ({@link Blacksmith}) with a method for + * + *

In this Factory Method example we have an interface ({@link Blacksmith}) with a method for * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses ( * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of * their liking. @@ -59,7 +58,7 @@ public App(Blacksmith blacksmith) { } /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java index 9d3a2cb0b6ff..7f3eafd605e9 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Blacksmith.java @@ -24,9 +24,7 @@ package com.iluwatar.factory.method; /** - * * The interface containing method for producing objects. - * */ public interface Blacksmith { diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java index adae5bd50b9a..0da783a34352 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java @@ -23,16 +23,26 @@ package com.iluwatar.factory.method; +import java.util.HashMap; +import java.util.Map; + /** - * * Concrete subclass for creating new objects. - * */ public class ElfBlacksmith implements Blacksmith { + private static Map ELFARSENAL; + + static { + ELFARSENAL = new HashMap<>(WeaponType.values().length); + for (WeaponType type : WeaponType.values()) { + ELFARSENAL.put(type, new ElfWeapon(type)); + } + } + @Override public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); + return ELFARSENAL.get(weaponType); } - + } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java index a2a86fe4455f..376b2ec34283 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java @@ -23,15 +23,25 @@ package com.iluwatar.factory.method; +import java.util.HashMap; +import java.util.Map; + /** - * * Concrete subclass for creating new objects. - * */ public class OrcBlacksmith implements Blacksmith { + private static Map ORCARSENAL; + + static { + ORCARSENAL = new HashMap<>(WeaponType.values().length); + for (WeaponType type : WeaponType.values()) { + ORCARSENAL.put(type, new OrcWeapon(type)); + } + } + @Override public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); + return ORCARSENAL.get(weaponType); } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java index 4cf38ee26628..73ab10dd6d01 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java @@ -24,9 +24,7 @@ package com.iluwatar.factory.method; /** - * - * WeaponType enumeration - * + * WeaponType enumeration. */ public enum WeaponType { diff --git a/faq.md b/faq.md deleted file mode 100644 index 107ee1e684e2..000000000000 --- a/faq.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -layout: page -link-title: FAQ -title: FAQ - Java Design Patterns -description: Java Design Pattern FAQ answers the most commonly asked design patterns questions. -permalink: /faq/ -icon: fa-question -page-index: 5 ---- - -### Q1: What is the difference between State and Strategy patterns? {#Q1} - -While the implementation is similar they solve different problems. The State -pattern deals with what state an object is in - it encapsulates state-dependent -behavior. -The Strategy pattern deals with how an object performs a certain task - it -encapsulates an algorithm. - -### Q2: What is the difference between Strategy and Template Method patterns? {#Q2} - -In Template Method the algorithm is chosen at compile time via inheritance. -With Strategy pattern the algorithm is chosen at runtime via composition. - -### Q3: What is the difference between Proxy and Decorator patterns? {#Q3} - -The difference is the intent of the patterns. While Proxy controls access to -the object Decorator is used to add responsibilities to the object. - -### Q4: What is the difference between Chain of Responsibility and Intercepting Filter patterns? {#Q4} - -While the implementations look similar there are differences. The Chain of -Responsibility forms a chain of request processors and the processors are then -executed one by one until the correct processor is found. In Intercepting -Filter the chain is constructed from filters and the whole chain is always -executed. - -### Q5: What is the difference between Visitor and Double Dispatch patterns? {#Q5} - -The Visitor pattern is a means of adding a new operation to existing classes. -Double dispatch is a means of dispatching function calls with respect to two -polymorphic types, rather than a single polymorphic type, which is what -languages like C++ and Java _do not_ support directly. - -### Q6: What are the differences between Flyweight and Object Pool patterns? {#Q6} - -They differ in the way they are used. - -Pooled objects can simultaneously be used by a single "client" only. For that, -a pooled object must be checked out from the pool, then it can be used by a -client, and then the client must return the object back to the pool. Multiple -instances of identical objects may exist, up to the maximal capacity of the -pool. - -In contrast, a Flyweight object is singleton, and it can be used simultaneously -by multiple clients. - -As for concurrent access, pooled objects can be mutable and they usually don't -need to be thread safe, as typically, only one thread is going to use a -specific instance at the same time. Flyweight must either be immutable (the -best option), or implement thread safety. - -As for performance and scalability, pools can become bottlenecks, if all the -pooled objects are in use and more clients need them, threads will become -blocked waiting for available object from the pool. This is not the case with -Flyweight. - -### Q7: What are the differences between FluentInterface and Builder patterns? {#Q7} - -Fluent interfaces are sometimes confused with the Builder pattern, because they share method chaining and a fluent usage. However, fluent interfaces are not primarily used to create shared (mutable) objects, but to configure complex objects without having to respecify the target object on every property change. - -### Q8: What is the difference between java.io.Serialization and Memento pattern? {#Q8} - -Memento is typically used to implement rollback/save-point support. Example we might want to mark the state of an object at a point in time, do some work and then decide to rollback to the previous state. - -On the other hand serialization may be used as a tool to save the state of an object into byte[] and preserving the contents in memory or disk. When someone invokes the memento to revert object's previous state then we can deserialize the information stored and recreate previous state. - -So Memento is a pattern and serialization is a tool that can be used to implement this pattern. Other ways to implement the pattern can be to clone the contents of the object and keep track of those clones. - - -### Q9: What's the difference between “API Gateway” and “Aggregator Microservices”? Isn't it the same? {#Q9} - -The API Gateway : Aggregate calls to microservices in a single location. The user makes a single call to the API Gateway, and the API Gateway then calls each relevant microservice. -Use the API Gateway pattern when you're also using the Microservices pattern and need a single point of aggregation for your microservice calls. - -Aggregator Microservices : The user makes a single call to the Aggregator, and the aggregator then calls each relevant microservice and collects the data, apply business logic to it, and further publish is as a REST Endpoint.Use the Aggregator Microservices pattern when you need a unified API for various microservices, regardless the client device. - - - diff --git a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java index 597f9d928f75..36766a568003 100644 --- a/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java +++ b/fluentinterface/src/main/java/com/iluwatar/fluentinterface/app/App.java @@ -23,21 +23,20 @@ package com.iluwatar.fluentinterface.app; -import static java.lang.String.valueOf; +import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; +import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; +import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.StringJoiner; import java.util.function.Function; import java.util.function.Predicate; -import com.iluwatar.fluentinterface.fluentiterable.FluentIterable; -import com.iluwatar.fluentinterface.fluentiterable.lazy.LazyFluentIterable; -import com.iluwatar.fluentinterface.fluentiterable.simple.SimpleFluentIterable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static java.lang.String.valueOf; /** * The Fluent Interface pattern is useful when you want to provide an easy readable, flowing API. @@ -61,7 +60,7 @@ public class App { public static void main(String[] args) { List integerList = new ArrayList<>(); - integerList.addAll(Arrays.asList(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, + integerList.addAll(List.of(1, -61, 14, -22, 18, -87, 6, 64, -82, 26, -98, 97, 45, 23, 2, -68, 45)); prettyPrint("The initial list contains: ", integerList); diff --git a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java index cfe52be7f1e5..4ee30d3e5734 100644 --- a/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java +++ b/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -25,21 +25,14 @@ import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Spliterator; import java.util.function.Consumer; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; /** * Date: 12/12/15 - 7:00 PM @@ -58,7 +51,7 @@ public abstract class FluentIterableTest { @Test public void testFirst() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List integers = List.of(1, 2, 3, 10, 9, 8); final Optional first = createFluentIterable(integers).first(); assertNotNull(first); assertTrue(first.isPresent()); @@ -75,7 +68,7 @@ public void testFirstEmptyCollection() throws Exception { @Test public void testFirstCount() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List integers = List.of(1, 2, 3, 10, 9, 8); final List first4 = createFluentIterable(integers) .first(4) .asList(); @@ -91,7 +84,7 @@ public void testFirstCount() throws Exception { @Test public void testFirstCountLessItems() throws Exception { - final List integers = Arrays.asList(1, 2, 3); + final List integers = List.of(1, 2, 3); final List first4 = createFluentIterable(integers) .first(4) .asList(); @@ -106,7 +99,7 @@ public void testFirstCountLessItems() throws Exception { @Test public void testLast() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List integers = List.of(1, 2, 3, 10, 9, 8); final Optional last = createFluentIterable(integers).last(); assertNotNull(last); assertTrue(last.isPresent()); @@ -123,7 +116,7 @@ public void testLastEmptyCollection() throws Exception { @Test public void testLastCount() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List integers = List.of(1, 2, 3, 10, 9, 8); final List last4 = createFluentIterable(integers) .last(4) .asList(); @@ -138,7 +131,7 @@ public void testLastCount() throws Exception { @Test public void testLastCountLessItems() throws Exception { - final List integers = Arrays.asList(1, 2, 3); + final List integers = List.of(1, 2, 3); final List last4 = createFluentIterable(integers) .last(4) .asList(); @@ -153,7 +146,7 @@ public void testLastCountLessItems() throws Exception { @Test public void testFilter() throws Exception { - final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List integers = List.of(1, 2, 3, 10, 9, 8); final List evenItems = createFluentIterable(integers) .filter(i -> i % 2 == 0) .asList(); @@ -167,7 +160,7 @@ public void testFilter() throws Exception { @Test public void testMap() throws Exception { - final List integers = Arrays.asList(1, 2, 3); + final List integers = List.of(1, 2, 3); final List longs = createFluentIterable(integers) .map(Integer::longValue) .asList(); @@ -181,7 +174,7 @@ public void testMap() throws Exception { @Test public void testForEach() { - final List integers = Arrays.asList(1, 2, 3); + final List integers = List.of(1, 2, 3); final Consumer consumer = mock(Consumer.class); createFluentIterable(integers).forEach(consumer); @@ -195,7 +188,7 @@ public void testForEach() { @Test public void testSpliterator() throws Exception { - final List integers = Arrays.asList(1, 2, 3); + final List integers = List.of(1, 2, 3); final Spliterator split = createFluentIterable(integers).spliterator(); assertNotNull(split); } diff --git a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java index c139e25b47b9..78f01474ff8c 100644 --- a/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java +++ b/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java @@ -26,7 +26,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -46,29 +45,24 @@ public class AlchemistShop { * Constructor */ public AlchemistShop() { - topShelf = new ArrayList<>(); - bottomShelf = new ArrayList<>(); - fillShelves(); - } - - private void fillShelves() { - PotionFactory factory = new PotionFactory(); - - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.STRENGTH)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - topShelf.add(factory.createPotion(PotionType.INVISIBILITY)); - topShelf.add(factory.createPotion(PotionType.STRENGTH)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - topShelf.add(factory.createPotion(PotionType.HEALING)); - - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.POISON)); - bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER)); - bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER)); + topShelf = List.of( + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.INVISIBILITY), + factory.createPotion(PotionType.STRENGTH), + factory.createPotion(PotionType.HEALING), + factory.createPotion(PotionType.HEALING) + ); + bottomShelf = List.of( + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.POISON), + factory.createPotion(PotionType.HOLY_WATER), + factory.createPotion(PotionType.HOLY_WATER) + ); } /** diff --git a/hexagonal/README.md b/hexagonal/README.md index 7d27f4b622b8..1e6f897d0297 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -29,9 +29,6 @@ Use Hexagonal Architecture pattern when ## Tutorials * [Build Maintainable Systems With Hexagonal Architecture](http://java-design-patterns.com/blog/build-maintainable-systems-with-hexagonal-architecture/) -## Presentations -* [Hexagonal Architecture](https://github.com/iluwatar/java-design-patterns/tree/master/hexagonal/etc/presentation.html) - ## Real world examples * [Apache Isis](https://isis.apache.org/) builds generic UI and REST API directly from the underlying domain objects diff --git a/hexagonal/etc/layers.png b/hexagonal/etc/layers.png deleted file mode 100644 index cb5a9c90bbe9..000000000000 Binary files a/hexagonal/etc/layers.png and /dev/null differ diff --git a/hexagonal/etc/ports_and_adapters.png b/hexagonal/etc/ports_and_adapters.png deleted file mode 100644 index d285045dea68..000000000000 Binary files a/hexagonal/etc/ports_and_adapters.png and /dev/null differ diff --git a/hexagonal/etc/ports_and_adapters.xml b/hexagonal/etc/ports_and_adapters.xml deleted file mode 100644 index 83edb95e02ef..000000000000 --- a/hexagonal/etc/ports_and_adapters.xml +++ /dev/null @@ -1,25 +0,0 @@ - -7Zpdk6I4FIZ/jbdbJAHEyx7nY/diqrqqd2tnLiOJSDUSK6ZHe3/9BkmUfFiDDqBM2TcNBwLxOe85nBOYoPl6/4XjzeorI7SYwIDsJ+jjBEKA4kj+qyzvtWUag9qQ8Zyok06Gl/w/qoyBsr7lhG6NEwVjhcg3pjFlZUlTYdgw52xnnrZkhXnXDc6oY3hJceFa/82JWNXWJApO9j9pnq30nUGgjixw+ppx9laq+00gWh7+6sNrrK+lzt+uMGG7hgl9mqA5Z0zUW+v9nBYVW42tHvf5zNHjvDktRZsBqB7wAxdvVM/4MC/xrlnIKW6qzRXd44yVE/RhQ3m+poLyk/X5ZPqwW+WCvmxwWo3aSYFI20qsC7kH5Ka6I+WC7s/OGhxZSI1RJi/N3+UpagBMFD4lL6D3dydnIa2lVcNRMFZGrASSHa99giQ3FCc/MzhKZmgaGcyOKBrMAPQwO2r7V5iFDrM549ThJgfJEKc/B7LMi2LOCsYP46oYg2kq7VvB2SttHCHxIo7ibhCGATARJshBqDNfk2AXoot+Lrpr4RFMk6UXXpwmdLHsCF5s6W/qwkMe+aEO4MW/GzwEPQmvJ3jT0cMDMxNeGA0GLxk7PDQ1H7VDKm82fnh2zoODwdPlz3jphdCUHoyGkx5oUeRdTS+iCQl99BK4QHFHxUoUWfQ89V5v9Fq0FXdOz9ZeMCC9Nk/ckjxVfa7cK1lJTWJ0n4tvje3vcjuotks5k2/Nne/6rJJ8zqsJHQ7Vd6PE6ZEtenJG7I2n1KhQBeYZFU0duJAbECMPRG3jtMAi/2HOwkdW3eGZ5XJ+Z7vECFjOqWevRjWbZOtCCJkXCu2Cvv7NzoUOjj7+7Ha+b1MwXOz7P6IefQwfPr7Qx33WNYNkR5s60nXuANkR9lnXDEIPWc8WNBvu2aJn+8v5JfDkF/V0Ac2nS3e5J/Hkntkj91yWe7S7O/U/OO/9/nzfWC5/+L6d70dfldsrOSEcbiXHs4R9ZeTUGdEXO41E2mX0TD3Rc1+Vue2gq6Mn6S963BX4Z8bF1hGBlLcwPW/GhFJGM4CUCRd5VsrdVDrz8FaoCpY8xcWTOrDOCSnOBWcH8YVmoYHzGDgNWYS+12pdxJe7SP/PVlKQZ1Q0ltVvtVEfXrRSojD3/w4NALvudd9hAN97x7ALQO6ywN90WwUDzqiS903h2CvFiZucZ32xcdvmv6RqMi6zFCtvjuZY4et851lN6g2N221+xAIv8Pb28RQHJhcwG04yOrU1uHxl6au0kLvBYz3dYOTi6S3doPF2irpKNAqe2I96mIIHWJ6Mr20XgF059dcuoD5axWEEoOsRQwDThwAuFECbfvE+Ox5dlxkCSB4CuFAAXbW8vpcRvldRHT4CfAK46WrhKAXQ5quzOxUAdAWAbrpkOEoBuE35E8Eb2Y//XuseVh+CPP1ZR+secvf0dXftkdMn9OjT/w== \ No newline at end of file diff --git a/hexagonal/etc/presentation.html b/hexagonal/etc/presentation.html deleted file mode 100644 index 35aca2bd3edc..000000000000 --- a/hexagonal/etc/presentation.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - Title - - - - - - - - - - diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java index 90dfd1fbdc18..8189303eb04a 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java @@ -31,7 +31,6 @@ import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; -import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -44,46 +43,47 @@ public class SampleData { private static final Random RANDOM = new Random(); static { - PLAYERS = new ArrayList<>(); - PLAYERS.add(new PlayerDetails("john@google.com", "312-342", "+3242434242")); - PLAYERS.add(new PlayerDetails("mary@google.com", "234-987", "+23452346")); - PLAYERS.add(new PlayerDetails("steve@google.com", "833-836", "+63457543")); - PLAYERS.add(new PlayerDetails("wayne@google.com", "319-826", "+24626")); - PLAYERS.add(new PlayerDetails("johnie@google.com", "983-322", "+3635635")); - PLAYERS.add(new PlayerDetails("andy@google.com", "934-734", "+0898245")); - PLAYERS.add(new PlayerDetails("richard@google.com", "536-738", "+09845325")); - PLAYERS.add(new PlayerDetails("kevin@google.com", "453-936", "+2423532")); - PLAYERS.add(new PlayerDetails("arnold@google.com", "114-988", "+5646346524")); - PLAYERS.add(new PlayerDetails("ian@google.com", "663-765", "+928394235")); - PLAYERS.add(new PlayerDetails("robin@google.com", "334-763", "+35448")); - PLAYERS.add(new PlayerDetails("ted@google.com", "735-964", "+98752345")); - PLAYERS.add(new PlayerDetails("larry@google.com", "734-853", "+043842423")); - PLAYERS.add(new PlayerDetails("calvin@google.com", "334-746", "+73294135")); - PLAYERS.add(new PlayerDetails("jacob@google.com", "444-766", "+358042354")); - PLAYERS.add(new PlayerDetails("edwin@google.com", "895-345", "+9752435")); - PLAYERS.add(new PlayerDetails("mary@google.com", "760-009", "+34203542")); - PLAYERS.add(new PlayerDetails("lolita@google.com", "425-907", "+9872342")); - PLAYERS.add(new PlayerDetails("bruno@google.com", "023-638", "+673824122")); - PLAYERS.add(new PlayerDetails("peter@google.com", "335-886", "+5432503945")); - PLAYERS.add(new PlayerDetails("warren@google.com", "225-946", "+9872341324")); - PLAYERS.add(new PlayerDetails("monica@google.com", "265-748", "+134124")); - PLAYERS.add(new PlayerDetails("ollie@google.com", "190-045", "+34453452")); - PLAYERS.add(new PlayerDetails("yngwie@google.com", "241-465", "+9897641231")); - PLAYERS.add(new PlayerDetails("lars@google.com", "746-936", "+42345298345")); - PLAYERS.add(new PlayerDetails("bobbie@google.com", "946-384", "+79831742")); - PLAYERS.add(new PlayerDetails("tyron@google.com", "310-992", "+0498837412")); - PLAYERS.add(new PlayerDetails("tyrell@google.com", "032-045", "+67834134")); - PLAYERS.add(new PlayerDetails("nadja@google.com", "000-346", "+498723")); - PLAYERS.add(new PlayerDetails("wendy@google.com", "994-989", "+987324454")); - PLAYERS.add(new PlayerDetails("luke@google.com", "546-634", "+987642435")); - PLAYERS.add(new PlayerDetails("bjorn@google.com", "342-874", "+7834325")); - PLAYERS.add(new PlayerDetails("lisa@google.com", "024-653", "+980742154")); - PLAYERS.add(new PlayerDetails("anton@google.com", "834-935", "+876423145")); - PLAYERS.add(new PlayerDetails("bruce@google.com", "284-936", "+09843212345")); - PLAYERS.add(new PlayerDetails("ray@google.com", "843-073", "+678324123")); - PLAYERS.add(new PlayerDetails("ron@google.com", "637-738", "+09842354")); - PLAYERS.add(new PlayerDetails("xavier@google.com", "143-947", "+375245")); - PLAYERS.add(new PlayerDetails("harriet@google.com", "842-404", "+131243252")); + PLAYERS = List.of( + new PlayerDetails("john@google.com", "312-342", "+3242434242"), + new PlayerDetails("mary@google.com", "234-987", "+23452346"), + new PlayerDetails("steve@google.com", "833-836", "+63457543"), + new PlayerDetails("wayne@google.com", "319-826", "+24626"), + new PlayerDetails("johnie@google.com", "983-322", "+3635635"), + new PlayerDetails("andy@google.com", "934-734", "+0898245"), + new PlayerDetails("richard@google.com", "536-738", "+09845325"), + new PlayerDetails("kevin@google.com", "453-936", "+2423532"), + new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), + new PlayerDetails("ian@google.com", "663-765", "+928394235"), + new PlayerDetails("robin@google.com", "334-763", "+35448"), + new PlayerDetails("ted@google.com", "735-964", "+98752345"), + new PlayerDetails("larry@google.com", "734-853", "+043842423"), + new PlayerDetails("calvin@google.com", "334-746", "+73294135"), + new PlayerDetails("jacob@google.com", "444-766", "+358042354"), + new PlayerDetails("edwin@google.com", "895-345", "+9752435"), + new PlayerDetails("mary@google.com", "760-009", "+34203542"), + new PlayerDetails("lolita@google.com", "425-907", "+9872342"), + new PlayerDetails("bruno@google.com", "023-638", "+673824122"), + new PlayerDetails("peter@google.com", "335-886", "+5432503945"), + new PlayerDetails("warren@google.com", "225-946", "+9872341324"), + new PlayerDetails("monica@google.com", "265-748", "+134124"), + new PlayerDetails("ollie@google.com", "190-045", "+34453452"), + new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), + new PlayerDetails("lars@google.com", "746-936", "+42345298345"), + new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), + new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), + new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), + new PlayerDetails("nadja@google.com", "000-346", "+498723"), + new PlayerDetails("wendy@google.com", "994-989", "+987324454"), + new PlayerDetails("luke@google.com", "546-634", "+987642435"), + new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), + new PlayerDetails("lisa@google.com", "024-653", "+980742154"), + new PlayerDetails("anton@google.com", "834-935", "+876423145"), + new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), + new PlayerDetails("ray@google.com", "843-073", "+678324123"), + new PlayerDetails("ron@google.com", "637-738", "+09842354"), + new PlayerDetails("xavier@google.com", "143-947", "+375245"), + new PlayerDetails("harriet@google.com", "842-404", "+131243252") + ); InMemoryBank wireTransfers = new InMemoryBank(); for (PlayerDetails player : PLAYERS) { wireTransfers.setFunds(player.getBankAccount(), diff --git a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java index c2a164353c08..3641b9a5c50c 100644 --- a/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java +++ b/hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java @@ -27,10 +27,9 @@ import com.iluwatar.hexagonal.domain.*; import org.slf4j.Logger; -import java.util.HashSet; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * Console implementation for lottery console service @@ -88,10 +87,7 @@ public void submitTicket(LotteryService service, Scanner scanner) { String numbers = readString( scanner ); try { String[] parts = numbers.split( "," ); - Set chosen = new HashSet<>(); - for (int i = 0; i < 4; i++) { - chosen.add( Integer.parseInt( parts[i] ) ); - } + Set chosen = Arrays.stream(parts).map(Integer::parseInt).collect(Collectors.toSet()); LotteryNumbers lotteryNumbers = LotteryNumbers.create( chosen ); LotteryTicket lotteryTicket = new LotteryTicket( new LotteryTicketId(), details, lotteryNumbers ); Optional id = service.submitTicket( lotteryTicket ); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java index 83699d6d413b..c17c5c1fdc39 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -25,13 +25,9 @@ import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.HashSet; +import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @@ -42,8 +38,7 @@ class LotteryNumbersTest { @Test void testGivenNumbers() { - LotteryNumbers numbers = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertEquals(numbers.getNumbers().size(), 4); assertTrue(numbers.getNumbers().contains(1)); assertTrue(numbers.getNumbers().contains(2)); @@ -53,8 +48,7 @@ void testGivenNumbers() { @Test void testNumbersCantBeModified() { - LotteryNumbers numbers = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertThrows(UnsupportedOperationException.class, () -> numbers.getNumbers().add(5)); } @@ -66,13 +60,10 @@ void testRandomNumbers() { @Test void testEquals() { - LotteryNumbers numbers1 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); - LotteryNumbers numbers2 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); + LotteryNumbers numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); assertEquals(numbers1, numbers2); - LotteryNumbers numbers3 = LotteryNumbers.create( - new HashSet<>(Arrays.asList(11, 12, 13, 14))); + LotteryNumbers numbers3 = LotteryNumbers.create(Set.of(11, 12, 13, 14)); assertNotEquals(numbers1, numbers3); } } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java index 4d06463d0c0f..927e2fcd19a9 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -33,14 +33,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; +import java.util.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @@ -76,13 +71,13 @@ void testLottery() { // players submit the lottery tickets Optional ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", - "123-12312", "+32425255", new HashSet<>(Arrays.asList(1, 2, 3, 4)))); + "123-12312", "+32425255", Set.of(1, 2, 3, 4))); assertTrue(ticket1.isPresent()); Optional ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", - "123-12312", "+32423455", new HashSet<>(Arrays.asList(11, 12, 13, 14)))); + "123-12312", "+32423455", Set.of(11, 12, 13, 14))); assertTrue(ticket2.isPresent()); Optional ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", - "123-12312", "+32421255", new HashSet<>(Arrays.asList(6, 8, 13, 19)))); + "123-12312", "+32421255", Set.of(6, 8, 13, 19))); assertTrue(ticket3.isPresent()); assertEquals(3, administration.getAllSubmittedTickets().size()); diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java index 5b9441a913cd..6d2e371c4bd0 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -25,8 +25,7 @@ import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.HashSet; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -39,14 +38,14 @@ class LotteryTicketTest { @Test void testEquals() { PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers1 = LotteryNumbers.create(new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers1 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); PlayerDetails details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); - LotteryNumbers numbers2 = LotteryNumbers.create(new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers2 = LotteryNumbers.create(Set.of(1, 2, 3, 4)); LotteryTicket ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); assertEquals(ticket1, ticket2); PlayerDetails details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); - LotteryNumbers numbers3 = LotteryNumbers.create(new HashSet<>(Arrays.asList(1, 2, 3, 8))); + LotteryNumbers numbers3 = LotteryNumbers.create(Set.of(1, 2, 3, 8)); LotteryTicket ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); assertNotEquals(ticket1, ticket3); } diff --git a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java b/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java index 2e67d2536a7e..2f02ca34e9f2 100644 --- a/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java +++ b/hexagonal/src/test/java/com/iluwatar/hexagonal/test/LotteryTestUtils.java @@ -23,15 +23,13 @@ package com.iluwatar.hexagonal.test; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - import com.iluwatar.hexagonal.domain.LotteryNumbers; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; +import java.util.Set; + /** * * Utilities for lottery tests @@ -43,7 +41,7 @@ public class LotteryTestUtils { * @return lottery ticket */ public static LotteryTicket createLotteryTicket() { - return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", new HashSet<>(Arrays.asList(1, 2, 3, 4))); + return createLotteryTicket("foo@bar.com", "12231-213132", "+99324554", Set.of(1, 2, 3, 4)); } /** diff --git a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java index 9c6dbc64feb5..3fb93f5af804 100644 --- a/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java +++ b/iterator/src/main/java/com/iluwatar/iterator/list/TreasureChest.java @@ -40,17 +40,17 @@ public class TreasureChest { * Constructor */ public TreasureChest() { - items = new ArrayList<>(); - items.add(new Item(ItemType.POTION, "Potion of courage")); - items.add(new Item(ItemType.RING, "Ring of shadows")); - items.add(new Item(ItemType.POTION, "Potion of wisdom")); - items.add(new Item(ItemType.POTION, "Potion of blood")); - items.add(new Item(ItemType.WEAPON, "Sword of silver +1")); - items.add(new Item(ItemType.POTION, "Potion of rust")); - items.add(new Item(ItemType.POTION, "Potion of healing")); - items.add(new Item(ItemType.RING, "Ring of armor")); - items.add(new Item(ItemType.WEAPON, "Steel halberd")); - items.add(new Item(ItemType.WEAPON, "Dagger of poison")); + items = List.of( + new Item(ItemType.POTION, "Potion of courage"), + new Item(ItemType.RING, "Ring of shadows"), + new Item(ItemType.POTION, "Potion of wisdom"), + new Item(ItemType.POTION, "Potion of blood"), + new Item(ItemType.WEAPON, "Sword of silver +1"), + new Item(ItemType.POTION, "Potion of rust"), + new Item(ItemType.POTION, "Potion of healing"), + new Item(ItemType.RING, "Ring of armor"), + new Item(ItemType.WEAPON, "Steel halberd"), + new Item(ItemType.WEAPON, "Dagger of poison")); } public Iterator iterator(ItemType itemType) { diff --git a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java index cac45c851c8f..350934590e51 100644 --- a/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/list/TreasureChestTest.java @@ -28,7 +28,6 @@ import static org.junit.jupiter.api.Assertions.fail; import com.iluwatar.iterator.Iterator; -import java.util.ArrayList; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -46,18 +45,18 @@ public class TreasureChestTest { * @return The set of all expected items in the chest */ public static List dataProvider() { - final List parameters = new ArrayList<>(); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); - parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of blood")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of rust")}); - parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of healing")}); - parameters.add(new Object[]{new Item(ItemType.RING, "Ring of armor")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}); - parameters.add(new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}); - return parameters; + return List.of( + new Object[]{new Item(ItemType.POTION, "Potion of courage")}, + new Object[]{new Item(ItemType.RING, "Ring of shadows")}, + new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}, + new Object[]{new Item(ItemType.POTION, "Potion of blood")}, + new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}, + new Object[]{new Item(ItemType.POTION, "Potion of rust")}, + new Object[]{new Item(ItemType.POTION, "Potion of healing")}, + new Object[]{new Item(ItemType.RING, "Ring of armor")}, + new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}, + new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")} + ); } /** diff --git a/layers/README.md b/layers/README.md index 49b74c175b96..3214a9e61756 100644 --- a/layers/README.md +++ b/layers/README.md @@ -12,7 +12,7 @@ tags: --- ## Intent -Layers is an architectural style where software responsibilities are +Layers is an architectural pattern where software responsibilities are divided among the different layers of the application. ![alt text](./etc/layers.png "Layers") @@ -24,6 +24,84 @@ Use the Layers architecture when * you want to prevent a change from propagating throughout the application * you want to make your application more maintainable and testable +## Explanation + +Real world example + +> Consider a web site displaying decorated cakes for weddings and such. Instead of the web page directly reaching into the database, it relies on a service to deliver this information. The service then queries the data layer to assimilate the needed information. + +In Plain Words + +> With Layers architectural pattern different concerns reside on separate layers. View layer is interested only in rendering, service layer assembles the requested data from various sources, and data layer gets the bits from the data storage. + +Wikipedia says + +> In software engineering, multitier architecture (often referred to as n-tier architecture) or multilayered architecture is a client–server architecture in which presentation, application processing, and data management functions are physically separated. + +**Programmatic Example** + +On the data layer, we keep our cake building blocks. Cakes consist of layers and topping. + +```java +@Entity +public class Cake { + + @Id + @GeneratedValue + private Long id; + + @OneToOne(cascade = CascadeType.REMOVE) + private CakeTopping topping; + + @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER) + private Set layers; +} +``` + +The service layer offers CakeBakingService for easy access to different aspects of cakes. + +```java +public interface CakeBakingService { + + void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; + + List getAllCakes(); + + void saveNewTopping(CakeToppingInfo toppingInfo); + + List getAvailableToppings(); + + void saveNewLayer(CakeLayerInfo layerInfo); + + List getAvailableLayers(); +} +``` + +On the top we have our view responsible of rendering the cakes. + +```java +public interface View { + + void render(); + +} + +public class CakeViewImpl implements View { + + private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); + + private CakeBakingService cakeBakingService; + + public CakeViewImpl(CakeBakingService cakeBakingService) { + this.cakeBakingService = cakeBakingService; + } + + public void render() { + cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); + } +} +``` + ## Credits * [Pattern Oriented Software Architecture Vol I-V](http://www.amazon.com/Pattern-Oriented-Software-Architecture-Volume-Patterns/dp/0471958697) diff --git a/layers/etc/layers.ucls b/layers/etc/layers.ucls index 060b391c0acf..a3cac547a033 100644 --- a/layers/etc/layers.ucls +++ b/layers/etc/layers.ucls @@ -1,7 +1,7 @@ - - - - - - - - - - - - - - - * This example demonstrates a traditional 3-layer architecture consisting of data access layer, business layer and - * presentation layer. - *

- * The data access layer is formed of Spring Data repositories CakeDao, CakeToppingDao and - * CakeLayerDao. The repositories can be used for CRUD operations on cakes, cake toppings and cake layers - * respectively. - *

- * The business layer is built on top of the data access layer. CakeBakingService offers methods to - * retrieve available cake toppings and cake layers and baked cakes. Also the service is used to create new cakes out of - * cake toppings and cake layers. - *

- * The presentation layer is built on the business layer and in this example it simply lists the cakes that have been - * baked. - *

- * We have applied so called strict layering which means that the layers can only access the classes directly beneath - * them. This leads the solution to create an additional set of DTOs ( CakeInfo, - * CakeToppingInfo, CakeLayerInfo) to translate data between layers. In other words, - * CakeBakingService cannot return entities ( Cake, CakeTopping, - * CakeLayer) directly since these reside on data access layer but instead translates these into business - * layer DTOs (CakeInfo, CakeToppingInfo, CakeLayerInfo) and returns them - * instead. This way the presentation layer does not have any knowledge of other layers than the business layer and thus - * is not affected by changes to them. - * - * @see Cake - * @see CakeTopping - * @see CakeLayer - * @see CakeDao - * @see CakeToppingDao - * @see CakeLayerDao - * @see CakeBakingService - * @see CakeInfo - * @see CakeToppingInfo - * @see CakeLayerInfo - * - */ -public class App { - - private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl(); - - /** - * Application entry point - * - * @param args Command line parameters - */ - public static void main(String[] args) { - - // initialize example data - initializeData(cakeBakingService); - - // create view and render it - CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService); - cakeView.render(); - } - - /** - * Initializes the example data - */ - private static void initializeData(CakeBakingService cakeBakingService) { - cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); - cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); - - cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); - cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); - - CakeInfo cake1 = - new CakeInfo(new CakeToppingInfo("candies", 0), Arrays.asList(new CakeLayerInfo( - "chocolate", 0), new CakeLayerInfo("banana", 0), new CakeLayerInfo("strawberry", 0))); - try { - cakeBakingService.bakeNewCake(cake1); - } catch (CakeBakingException e) { - e.printStackTrace(); - } - CakeInfo cake2 = - new CakeInfo(new CakeToppingInfo("cherry", 0), Arrays.asList( - new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("lemon", 0), new CakeLayerInfo( - "strawberry", 0))); - try { - cakeBakingService.bakeNewCake(cake2); - } catch (CakeBakingException e) { - e.printStackTrace(); - } - } -} diff --git a/layers/src/main/java/com/iluwatar/layers/app/App.java b/layers/src/main/java/com/iluwatar/layers/app/App.java new file mode 100644 index 000000000000..b7d7b5507334 --- /dev/null +++ b/layers/src/main/java/com/iluwatar/layers/app/App.java @@ -0,0 +1,134 @@ +/* + * 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.layers.app; + +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; +import com.iluwatar.layers.exception.CakeBakingException; +import com.iluwatar.layers.service.CakeBakingService; +import com.iluwatar.layers.service.CakeBakingServiceImpl; +import com.iluwatar.layers.view.CakeViewImpl; +import java.util.List; + +/** + * Layers is an architectural style where software responsibilities are divided among the + * different layers of the application. + * + *

This example demonstrates a traditional 3-layer architecture consisting of data access + * layer, business layer and presentation layer. + * + *

The data access layer is formed of Spring Data repositories CakeDao, + * CakeToppingDao and CakeLayerDao. The repositories can be used + * for CRUD operations on cakes, cake toppings and cake layers respectively. + * + *

The business layer is built on top of the data access layer. CakeBakingService + * offers methods to retrieve available cake toppings and cake layers and baked cakes. Also the + * service is used to create new cakes out of cake toppings and cake layers. + * + *

The presentation layer is built on the business layer and in this example it simply lists + * the cakes that have been baked. + * + *

We have applied so called strict layering which means that the layers can only access the + * classes directly beneath them. This leads the solution to create an additional set of DTOs + * ( CakeInfo, CakeToppingInfo, CakeLayerInfo) to translate + * data between layers. In other words, CakeBakingService cannot return entities + * ( Cake, CakeTopping, CakeLayer) directly since these + * reside on data access layer but instead translates these into business layer DTOs + * (CakeInfo, CakeToppingInfo, CakeLayerInfo) and returns + * them instead. This way the presentation layer does not have any knowledge of other layers than + * the business layer and thus is not affected by changes to them. + * + * @see Cake + * @see CakeTopping + * @see CakeLayer + * @see CakeDao + * @see CakeToppingDao + * @see CakeLayerDao + * @see CakeBakingService + * @see CakeInfo + * @see CakeToppingInfo + * @see CakeLayerInfo + * + */ +public class App { + + private static CakeBakingService cakeBakingService = new CakeBakingServiceImpl(); + + /** + * Application entry point. + * + * @param args Command line parameters + */ + public static void main(String[] args) { + + // initialize example data + initializeData(cakeBakingService); + + // create view and render it + CakeViewImpl cakeView = new CakeViewImpl(cakeBakingService); + cakeView.render(); + } + + /** + * Initializes the example data. + */ + private static void initializeData(CakeBakingService cakeBakingService) { + cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); + cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); + + cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); + cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); + + CakeInfo cake1 = + new CakeInfo(new CakeToppingInfo("candies", 0), List.of( + new CakeLayerInfo("chocolate", 0), + new CakeLayerInfo("banana", 0), + new CakeLayerInfo("strawberry", 0))); + try { + cakeBakingService.bakeNewCake(cake1); + } catch (CakeBakingException e) { + e.printStackTrace(); + } + CakeInfo cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), List.of( + new CakeLayerInfo("vanilla", 0), + new CakeLayerInfo("lemon", 0), + new CakeLayerInfo("strawberry", 0))); + try { + cakeBakingService.bakeNewCake(cake2); + } catch (CakeBakingException e) { + e.printStackTrace(); + } + } +} diff --git a/layers/src/main/java/com/iluwatar/layers/CakeDao.java b/layers/src/main/java/com/iluwatar/layers/dao/CakeDao.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeDao.java rename to layers/src/main/java/com/iluwatar/layers/dao/CakeDao.java index 3128fe973320..7013bd5dcd24 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeDao.java +++ b/layers/src/main/java/com/iluwatar/layers/dao/CakeDao.java @@ -21,15 +21,14 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dao; +import com.iluwatar.layers.entity.Cake; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** - * - * CRUD repository for cakes - * + * CRUD repository for cakes. */ @Repository public interface CakeDao extends CrudRepository { diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java b/layers/src/main/java/com/iluwatar/layers/dao/CakeLayerDao.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java rename to layers/src/main/java/com/iluwatar/layers/dao/CakeLayerDao.java index 15d35c0df09b..5907ff7a77fc 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayerDao.java +++ b/layers/src/main/java/com/iluwatar/layers/dao/CakeLayerDao.java @@ -21,15 +21,14 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dao; +import com.iluwatar.layers.entity.CakeLayer; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** - * - * CRUD repository for cake layers - * + * CRUD repository for cake layers. */ @Repository public interface CakeLayerDao extends CrudRepository { diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java b/layers/src/main/java/com/iluwatar/layers/dao/CakeToppingDao.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java rename to layers/src/main/java/com/iluwatar/layers/dao/CakeToppingDao.java index 5ae63e3458d2..cddac432ea18 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeToppingDao.java +++ b/layers/src/main/java/com/iluwatar/layers/dao/CakeToppingDao.java @@ -21,15 +21,14 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dao; +import com.iluwatar.layers.entity.CakeTopping; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** - * - * CRUD repository cake toppings - * + * CRUD repository cake toppings. */ @Repository public interface CakeToppingDao extends CrudRepository { diff --git a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java b/layers/src/main/java/com/iluwatar/layers/dto/CakeInfo.java similarity index 95% rename from layers/src/main/java/com/iluwatar/layers/CakeInfo.java rename to layers/src/main/java/com/iluwatar/layers/dto/CakeInfo.java index 3957dbeda77a..98d048e1a9e8 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/dto/CakeInfo.java @@ -21,15 +21,13 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dto; import java.util.List; import java.util.Optional; /** - * - * DTO for cakes - * + * DTO for cakes. */ public class CakeInfo { @@ -38,7 +36,7 @@ public class CakeInfo { public final List cakeLayerInfos; /** - * Constructor + * Constructor. */ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = Optional.of(id); @@ -47,7 +45,7 @@ public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List ca } /** - * Constructor + * Constructor. */ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerInfos) { this.id = Optional.empty(); @@ -56,7 +54,7 @@ public CakeInfo(CakeToppingInfo cakeToppingInfo, List cakeLayerIn } /** - * Calculate calories + * Calculate calories. */ public int calculateTotalCalories() { int total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0; diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java b/layers/src/main/java/com/iluwatar/layers/dto/CakeLayerInfo.java similarity index 94% rename from layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java rename to layers/src/main/java/com/iluwatar/layers/dto/CakeLayerInfo.java index 692cf6c444b4..67774a4083ac 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayerInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/dto/CakeLayerInfo.java @@ -21,14 +21,12 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dto; import java.util.Optional; /** - * - * DTO for cake layers - * + * DTO for cake layers. */ public class CakeLayerInfo { @@ -37,7 +35,7 @@ public class CakeLayerInfo { public final int calories; /** - * Constructor + * Constructor. */ public CakeLayerInfo(Long id, String name, int calories) { this.id = Optional.of(id); @@ -46,7 +44,7 @@ public CakeLayerInfo(Long id, String name, int calories) { } /** - * Constructor + * Constructor. */ public CakeLayerInfo(String name, int calories) { this.id = Optional.empty(); diff --git a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java b/layers/src/main/java/com/iluwatar/layers/dto/CakeToppingInfo.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java rename to layers/src/main/java/com/iluwatar/layers/dto/CakeToppingInfo.java index dc138778a172..62dc5ccd2fdb 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeToppingInfo.java +++ b/layers/src/main/java/com/iluwatar/layers/dto/CakeToppingInfo.java @@ -21,14 +21,12 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.dto; import java.util.Optional; /** - * - * DTO for cake toppings - * + * DTO for cake toppings. */ public class CakeToppingInfo { @@ -37,7 +35,7 @@ public class CakeToppingInfo { public final int calories; /** - * Constructor + * Constructor. */ public CakeToppingInfo(Long id, String name, int calories) { this.id = Optional.of(id); @@ -46,7 +44,7 @@ public CakeToppingInfo(Long id, String name, int calories) { } /** - * Constructor + * Constructor. */ public CakeToppingInfo(String name, int calories) { this.id = Optional.empty(); @@ -56,6 +54,7 @@ public CakeToppingInfo(String name, int calories) { @Override public String toString() { - return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); + return String.format("CakeToppingInfo id=%d name=%s calories=%d", + id.orElse(-1L), name, calories); } } diff --git a/layers/src/main/java/com/iluwatar/layers/Cake.java b/layers/src/main/java/com/iluwatar/layers/entity/Cake.java similarity index 95% rename from layers/src/main/java/com/iluwatar/layers/Cake.java rename to layers/src/main/java/com/iluwatar/layers/entity/Cake.java index 3f866974cce4..83511d1585d5 100644 --- a/layers/src/main/java/com/iluwatar/layers/Cake.java +++ b/layers/src/main/java/com/iluwatar/layers/entity/Cake.java @@ -21,7 +21,7 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.entity; import java.util.HashSet; import java.util.Set; @@ -35,9 +35,7 @@ import javax.persistence.OneToOne; /** - * - * Cake entity - * + * Cake entity. */ @Entity public class Cake { @@ -76,7 +74,7 @@ public Set getLayers() { return layers; } - public final void setLayers(Set layers) { + public void setLayers(Set layers) { this.layers = layers; } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java b/layers/src/main/java/com/iluwatar/layers/entity/CakeLayer.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeLayer.java rename to layers/src/main/java/com/iluwatar/layers/entity/CakeLayer.java index 5fed0db22eb3..3e3ab8a0e587 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeLayer.java +++ b/layers/src/main/java/com/iluwatar/layers/entity/CakeLayer.java @@ -21,7 +21,7 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; @@ -30,9 +30,7 @@ import javax.persistence.ManyToOne; /** - * - * CakeLayer entity - * + * CakeLayer entity. */ @Entity public class CakeLayer { @@ -48,7 +46,8 @@ public class CakeLayer { @ManyToOne(cascade = CascadeType.ALL) private Cake cake; - public CakeLayer() {} + public CakeLayer() { + } public CakeLayer(String name, int calories) { this.setName(name); @@ -67,7 +66,7 @@ public String getName() { return name; } - public final void setName(String name) { + public void setName(String name) { this.name = name; } @@ -75,7 +74,7 @@ public int getCalories() { return calories; } - public final void setCalories(int calories) { + public void setCalories(int calories) { this.calories = calories; } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java b/layers/src/main/java/com/iluwatar/layers/entity/CakeTopping.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeTopping.java rename to layers/src/main/java/com/iluwatar/layers/entity/CakeTopping.java index d49fd50723d6..ae5277499f8e 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeTopping.java +++ b/layers/src/main/java/com/iluwatar/layers/entity/CakeTopping.java @@ -21,7 +21,7 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; @@ -30,9 +30,7 @@ import javax.persistence.OneToOne; /** - * - * CakeTopping entity - * + * CakeTopping entity. */ @Entity public class CakeTopping { @@ -48,7 +46,8 @@ public class CakeTopping { @OneToOne(cascade = CascadeType.ALL) private Cake cake; - public CakeTopping() {} + public CakeTopping() { + } public CakeTopping(String name, int calories) { this.setName(name); @@ -67,11 +66,11 @@ public String getName() { return name; } - public final void setName(String name) { + public void setName(String name) { this.name = name; } - public final int getCalories() { + public int getCalories() { return calories; } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java b/layers/src/main/java/com/iluwatar/layers/exception/CakeBakingException.java similarity index 91% rename from layers/src/main/java/com/iluwatar/layers/CakeBakingException.java rename to layers/src/main/java/com/iluwatar/layers/exception/CakeBakingException.java index 0c6607b05a09..a027fee98e28 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingException.java +++ b/layers/src/main/java/com/iluwatar/layers/exception/CakeBakingException.java @@ -21,18 +21,17 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.exception; /** - * - * Custom exception used in cake baking - * + * Custom exception used in cake baking. */ public class CakeBakingException extends Exception { private static final long serialVersionUID = 1L; - public CakeBakingException() {} + public CakeBakingException() { + } public CakeBakingException(String message) { super(message); diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingService.java similarity index 77% rename from layers/src/main/java/com/iluwatar/layers/CakeBakingService.java rename to layers/src/main/java/com/iluwatar/layers/service/CakeBakingService.java index 2bface9681ac..1ccfa5cf83f9 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingService.java +++ b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingService.java @@ -21,44 +21,46 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +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.exception.CakeBakingException; import java.util.List; /** - * - * Service for cake baking operations - * + * Service for cake baking operations. */ public interface CakeBakingService { /** - * Bakes new cake according to parameters + * Bakes new cake according to parameters. */ void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException; /** - * Get all cakes + * Get all cakes. */ List getAllCakes(); /** - * Store new cake topping + * Store new cake topping. */ void saveNewTopping(CakeToppingInfo toppingInfo); /** - * Get available cake toppings + * Get available cake toppings. */ List getAvailableToppings(); /** - * Add new cake layer + * Add new cake layer. */ void saveNewLayer(CakeLayerInfo layerInfo); /** - * Get available cake layers + * Get available cake layers. */ List getAvailableLayers(); } diff --git a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java similarity index 91% rename from layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java rename to layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java index 4b48b7345081..403816421a4b 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeBakingServiceImpl.java +++ b/layers/src/main/java/com/iluwatar/layers/service/CakeBakingServiceImpl.java @@ -21,8 +21,18 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +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.entity.Cake; +import com.iluwatar.layers.entity.CakeLayer; +import com.iluwatar.layers.entity.CakeTopping; +import com.iluwatar.layers.exception.CakeBakingException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -37,9 +47,7 @@ import org.springframework.transaction.annotation.Transactional; /** - * - * Implementation of CakeBakingService - * + * Implementation of CakeBakingService. */ @Service @Transactional @@ -73,7 +81,8 @@ public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { } } CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class); - Optional topping = toppingBean.findById(matchingToppings.iterator().next().getId()); + Optional topping = toppingBean.findById( + matchingToppings.iterator().next().getId()); CakeDao cakeBean = context.getBean(CakeDao.class); if (topping.isPresent()) { Cake cake = new Cake(); diff --git a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java b/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java similarity index 92% rename from layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java rename to layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java index 67c409793055..5fcaac776b7a 100644 --- a/layers/src/main/java/com/iluwatar/layers/CakeViewImpl.java +++ b/layers/src/main/java/com/iluwatar/layers/view/CakeViewImpl.java @@ -21,15 +21,14 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.view; +import com.iluwatar.layers.service.CakeBakingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * View implementation for displaying cakes - * + * View implementation for displaying cakes. */ public class CakeViewImpl implements View { diff --git a/layers/src/main/java/com/iluwatar/layers/View.java b/layers/src/main/java/com/iluwatar/layers/view/View.java similarity index 95% rename from layers/src/main/java/com/iluwatar/layers/View.java rename to layers/src/main/java/com/iluwatar/layers/view/View.java index e2456d524d33..0002b23f6447 100644 --- a/layers/src/main/java/com/iluwatar/layers/View.java +++ b/layers/src/main/java/com/iluwatar/layers/view/View.java @@ -21,12 +21,10 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.view; /** - * - * View interface - * + * View interface. */ public interface View { diff --git a/layers/src/test/java/com/iluwatar/layers/AppTest.java b/layers/src/test/java/com/iluwatar/layers/app/AppTest.java similarity index 95% rename from layers/src/test/java/com/iluwatar/layers/AppTest.java rename to layers/src/test/java/com/iluwatar/layers/app/AppTest.java index b95e899d7d5b..10d224a8e283 100644 --- a/layers/src/test/java/com/iluwatar/layers/AppTest.java +++ b/layers/src/test/java/com/iluwatar/layers/app/AppTest.java @@ -21,8 +21,9 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.app; +import com.iluwatar.layers.app.App; import org.junit.jupiter.api.Test; /** diff --git a/layers/src/test/java/com/iluwatar/layers/CakeTest.java b/layers/src/test/java/com/iluwatar/layers/entity/CakeTest.java similarity index 90% rename from layers/src/test/java/com/iluwatar/layers/CakeTest.java rename to layers/src/test/java/com/iluwatar/layers/entity/CakeTest.java index 28bbf02601c8..3c0051bbc0dc 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeTest.java +++ b/layers/src/test/java/com/iluwatar/layers/entity/CakeTest.java @@ -21,8 +21,11 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.entity; +import com.iluwatar.layers.entity.Cake; +import com.iluwatar.layers.entity.CakeLayer; +import com.iluwatar.layers.entity.CakeTopping; import org.junit.jupiter.api.Test; import java.util.HashSet; @@ -66,11 +69,10 @@ public void testSetLayers() { assertNotNull(cake.getLayers()); assertTrue(cake.getLayers().isEmpty()); - final Set expectedLayers = new HashSet<>(); - expectedLayers.add(new CakeLayer("layer1", 1000)); - expectedLayers.add(new CakeLayer("layer2", 2000)); - expectedLayers.add(new CakeLayer("layer3", 3000)); - + final Set expectedLayers = Set.of( + new CakeLayer("layer1", 1000), + new CakeLayer("layer2", 2000), + new CakeLayer("layer3", 3000)); cake.setLayers(expectedLayers); assertEquals(expectedLayers, cake.getLayers()); } @@ -111,7 +113,7 @@ public void testToString() { cake.setTopping(topping); cake.addLayer(layer); - final String expected = "id=1234 topping=id=2345 name=topping calories=20 " + final String expected = "id=1234 topping=id=2345 name=topping calories=20 " + "layers=[id=3456 name=layer calories=100]"; assertEquals(expected, cake.toString()); diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java b/layers/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java similarity index 95% rename from layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java rename to layers/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java index 4535be67889d..8c96b7d8e8f0 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java +++ b/layers/src/test/java/com/iluwatar/layers/exception/CakeBakingExceptionTest.java @@ -21,8 +21,9 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.exception; +import com.iluwatar.layers.exception.CakeBakingException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java b/layers/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java similarity index 89% rename from layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java rename to layers/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java index 681b37e05870..41c8b17537ff 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java +++ b/layers/src/test/java/com/iluwatar/layers/service/CakeBakingServiceImplTest.java @@ -21,19 +21,19 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +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.exception.CakeBakingException; +import com.iluwatar.layers.service.CakeBakingServiceImpl; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Date: 12/15/15 - 9:55 PM @@ -108,7 +108,7 @@ public void testBakeCakes() throws CakeBakingException { service.saveNewLayer(layer2); service.saveNewLayer(layer3); - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); final List allCakes = service.getAllCakes(); @@ -136,7 +136,7 @@ public void testBakeCakeMissingTopping() { final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000); assertThrows(CakeBakingException.class, () -> { - service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(missingTopping, List.of(layer1, layer2))); }); } @@ -156,7 +156,7 @@ public void testBakeCakeMissingLayer() { final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000); assertThrows(CakeBakingException.class, () -> { - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); + service.bakeNewCake(new CakeInfo(topping1, List.of(layer1, missingLayer))); }); } @@ -178,7 +178,7 @@ public void testBakeCakesUsedLayer() throws CakeBakingException { service.saveNewLayer(layer1); service.saveNewLayer(layer2); - service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(topping1, List.of(layer1, layer2))); assertThrows(CakeBakingException.class, () -> { service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); }); diff --git a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java similarity index 85% rename from layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java rename to layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java index 56feae2e092f..c396208b729b 100644 --- a/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java +++ b/layers/src/test/java/com/iluwatar/layers/view/CakeViewImplTest.java @@ -21,17 +21,21 @@ * THE SOFTWARE. */ -package com.iluwatar.layers; +package com.iluwatar.layers.view; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import com.iluwatar.layers.dto.CakeInfo; +import com.iluwatar.layers.dto.CakeLayerInfo; +import com.iluwatar.layers.dto.CakeToppingInfo; +import com.iluwatar.layers.service.CakeBakingService; +import com.iluwatar.layers.view.CakeViewImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -64,14 +68,13 @@ public void tearDown() { @Test public void testRender() { - final List layers = new ArrayList<>(); - layers.add(new CakeLayerInfo("layer1", 1000)); - layers.add(new CakeLayerInfo("layer2", 2000)); - layers.add(new CakeLayerInfo("layer3", 3000)); + final List layers = List.of( + new CakeLayerInfo("layer1", 1000), + new CakeLayerInfo("layer2", 2000), + new CakeLayerInfo("layer3", 3000)); - final List cakes = new ArrayList<>(); final CakeInfo cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); - cakes.add(cake); + final List cakes = List.of(cake); final CakeBakingService bakingService = mock(CakeBakingService.class); when(bakingService.getAllCakes()).thenReturn(cakes); diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java index f099ed9466a0..524cf32170dc 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/bully/BullyMessageManagerTest.java @@ -24,12 +24,9 @@ package com.iluwatar.leaderelection.bully; import com.iluwatar.leaderelection.*; -import com.iluwatar.leaderelection.ring.RingInstance; -import com.iluwatar.leaderelection.ring.RingMessageManager; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; -import java.util.HashMap; import java.util.Map; import java.util.Queue; @@ -43,8 +40,7 @@ public class BullyMessageManagerTest { @Test public void testSendHeartbeatMessage() { Instance instance1 = new BullyInstance(null, 1, 1); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); + Map instanceMap = Map.of(1, instance1); MessageManager messageManager = new BullyMessageManager(instanceMap); assertTrue(messageManager.sendHeartbeatMessage(1)); } @@ -56,11 +52,7 @@ public void testSendElectionMessageNotAccepted() { Instance instance2 = new BullyInstance(null, 1, 2); Instance instance3 = new BullyInstance(null, 1, 3); Instance instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); - instanceMap.put(4, instance4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); MessageManager messageManager = new BullyMessageManager(instanceMap); boolean result = messageManager.sendElectionMessage(3, "3"); @@ -84,11 +76,7 @@ public void testElectionMessageAccepted() { Instance instance2 = new BullyInstance(null, 1, 2); Instance instance3 = new BullyInstance(null, 1, 3); Instance instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); - instanceMap.put(4, instance4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); MessageManager messageManager = new BullyMessageManager(instanceMap); boolean result = messageManager.sendElectionMessage(2, "2"); @@ -102,11 +90,7 @@ public void testSendLeaderMessage() { Instance instance2 = new BullyInstance(null, 1, 2); Instance instance3 = new BullyInstance(null, 1, 3); Instance instance4 = new BullyInstance(null, 1, 4); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); - instanceMap.put(4, instance4); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3, 4, instance4); instance1.setAlive(false); MessageManager messageManager = new BullyMessageManager(instanceMap); messageManager.sendLeaderMessage(2, 2); @@ -129,10 +113,7 @@ public void testSendHeartbeatInvokeMessage() { Instance instance1 = new BullyInstance(null, 1, 1); Instance instance2 = new BullyInstance(null, 1, 2); Instance instance3 = new BullyInstance(null, 1, 3); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); MessageManager messageManager = new BullyMessageManager(instanceMap); messageManager.sendHeartbeatInvokeMessage(2); Message message = new Message(MessageType.HEARTBEAT_INVOKE, ""); diff --git a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java index 82a5a5936f59..d8429f02b05f 100644 --- a/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java +++ b/leader-election/src/test/java/com/iluwatar/leaderelection/ring/RingMessageManagerTest.java @@ -27,7 +27,6 @@ import org.junit.jupiter.api.Test; import java.lang.reflect.Field; -import java.util.HashMap; import java.util.Map; import java.util.Queue; @@ -41,8 +40,7 @@ public class RingMessageManagerTest { @Test public void testSendHeartbeatMessage() { Instance instance1 = new RingInstance(null, 1, 1); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); + Map instanceMap = Map.of(1, instance1); MessageManager messageManager = new RingMessageManager(instanceMap); assertTrue(messageManager.sendHeartbeatMessage(1)); } @@ -53,10 +51,7 @@ public void testSendElectionMessage() { Instance instance1 = new RingInstance(null, 1, 1); Instance instance2 = new RingInstance(null, 1, 2); Instance instance3 = new RingInstance(null, 1, 3); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); MessageManager messageManager = new RingMessageManager(instanceMap); String messageContent = "2"; messageManager.sendElectionMessage(2, messageContent); @@ -78,10 +73,7 @@ public void testSendLeaderMessage() { Instance instance1 = new RingInstance(null, 1, 1); Instance instance2 = new RingInstance(null, 1, 2); Instance instance3 = new RingInstance(null, 1, 3); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); MessageManager messageManager = new RingMessageManager(instanceMap); String messageContent = "3"; messageManager.sendLeaderMessage(2, 3); @@ -102,10 +94,7 @@ public void testSendHeartbeatInvokeMessage() { Instance instance1 = new RingInstance(null, 1, 1); Instance instance2 = new RingInstance(null, 1, 2); Instance instance3 = new RingInstance(null, 1, 3); - Map instanceMap = new HashMap<>(); - instanceMap.put(1, instance1); - instanceMap.put(2, instance2); - instanceMap.put(3, instance3); + Map instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3); MessageManager messageManager = new RingMessageManager(instanceMap); messageManager.sendHeartbeatInvokeMessage(2); Message ringMessage = new Message(MessageType.HEARTBEAT_INVOKE, ""); diff --git a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java index b7092347b840..951f8e166c89 100644 --- a/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java +++ b/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -32,7 +32,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; @@ -50,7 +49,7 @@ public class PartyMemberTest { static Collection[]> dataProvider() { - return Arrays.asList( + return List.of( new Supplier[]{Hobbit::new}, new Supplier[]{Hunter::new}, new Supplier[]{Rogue::new}, diff --git a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java index 2c201ead22e6..303dfda4fa13 100644 --- a/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java +++ b/naked-objects/fixture/src/main/java/domainapp/fixture/scenarios/RecreateSimpleObjects.java @@ -23,17 +23,14 @@ package domainapp.fixture.scenarios; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import com.google.common.collect.Lists; - -import org.apache.isis.applib.fixturescripts.FixtureScript; - import domainapp.dom.modules.simple.SimpleObject; import domainapp.fixture.modules.simple.SimpleObjectCreate; import domainapp.fixture.modules.simple.SimpleObjectsTearDown; +import org.apache.isis.applib.fixturescripts.FixtureScript; + +import java.util.Collections; +import java.util.List; /** @@ -41,8 +38,8 @@ */ public class RecreateSimpleObjects extends FixtureScript { - public final List names = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Baz", - "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); + public final List names = Collections.unmodifiableList(List.of("Foo", "Bar", "Baz", + "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); // region > number (optional input) private Integer number; diff --git a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java index b946f80981d7..d4ca42948b81 100644 --- a/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java +++ b/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java @@ -25,15 +25,10 @@ import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static java.time.Duration.ofMillis; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTimeout; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Date: 12/27/15 - 1:05 AM @@ -115,7 +110,7 @@ public void testConcurrentCheckinCheckout() { // The order of the returned instances is not determined, so just put them in a list // and verify if both expected instances are in there. - final List oliphaunts = Arrays.asList(pool.checkOut(), pool.checkOut()); + final List oliphaunts = List.of(pool.checkOut(), pool.checkOut()); assertEquals(pool.toString(), "Pool available=0 inUse=2"); assertTrue(oliphaunts.contains(firstOliphaunt)); assertTrue(oliphaunts.contains(secondOliphaunt)); diff --git a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java index c43c592da611..66ec45fdb62e 100644 --- a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java @@ -23,7 +23,6 @@ package com.iluwatar.observer; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -36,12 +35,11 @@ public class HobbitsTest extends WeatherObserverTest { @Override public Collection dataProvider() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); - testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); - testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); - testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); - return testData; + return List.of( + new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}, + new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}, + new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}, + new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); } /** diff --git a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java index b2c0fcbaca10..ff615df3c94e 100644 --- a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java @@ -23,7 +23,6 @@ package com.iluwatar.observer; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -36,12 +35,11 @@ public class OrcsTest extends WeatherObserverTest { @Override public Collection dataProvider() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); - testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); - testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); - testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); - return testData; + return List.of( + new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}, + new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}, + new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}, + new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); } /** diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java index 93e68a9f1ac1..dd0e6d6bf5f4 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java @@ -25,7 +25,6 @@ import com.iluwatar.observer.WeatherType; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -38,12 +37,12 @@ public class GHobbitsTest extends ObserverTest { @Override public Collection dataProvider() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); - testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); - testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); - testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); - return testData; + return List.of( + new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}, + new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}, + new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}, + new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."} + ); } /** diff --git a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java index b73b105199cc..396de445669f 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java +++ b/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java @@ -25,7 +25,6 @@ import com.iluwatar.observer.WeatherType; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -38,12 +37,12 @@ public class OrcsTest extends ObserverTest { @Override public Collection dataProvider() { - final List testData = new ArrayList<>(); - testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); - testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); - testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); - testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); - return testData; + return List.of( + new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}, + new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}, + new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}, + new Object[]{WeatherType.COLD, "The orcs are freezing cold."} + ); } /** 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 05aa660880c1..314846a3dbe5 100644 --- a/partial-response/src/main/java/com/iluwatar/partialresponse/App.java +++ b/partial-response/src/main/java/com/iluwatar/partialresponse/App.java @@ -26,7 +26,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.HashMap; import java.util.Map; /** @@ -47,10 +46,13 @@ public class App { * @param args program argument. */ public static void main(String[] args) throws Exception { - Map videos = new HashMap<>(); - videos.put(1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English")); - videos.put(2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese")); - videos.put(3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English")); + 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")); VideoResource videoResource = new VideoResource(new FieldJsonMapper(), videos); diff --git a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java index c28613f4a8c7..85f240fa03db 100644 --- a/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java +++ b/partial-response/src/test/java/com/iluwatar/partialresponse/VideoResourceTest.java @@ -29,7 +29,6 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; @@ -49,10 +48,13 @@ public class VideoResourceTest { @Before public void setUp() { - Map videos = new HashMap<>(); - videos.put(1, new Video(1, "Avatar", 178, "epic science fiction film", "James Cameron", "English")); - videos.put(2, new Video(2, "Godzilla Resurgence", 120, "Action & drama movie|", "Hideaki Anno", "Japanese")); - videos.put(3, new Video(3, "Interstellar", 169, "Adventure & Sci-Fi", "Christopher Nolan", "English")); + 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")); resource = new VideoResource(fieldJsonMapper, videos); } diff --git a/pom.xml b/pom.xml index b6c1b4472a88..8b8139f790e3 100644 --- a/pom.xml +++ b/pom.xml @@ -406,6 +406,31 @@ + + + org.commonjava.maven.plugins + directory-maven-plugin + 0.3.1 + + + directories + + directory-of + + initialize + + projectRoot + + com.iluwatar + java-design-patterns + + + + + + com.mycila license-maven-plugin @@ -417,11 +442,14 @@ true - license-plugin-header-style.xml + ${projectRoot}${file.separator}license-plugin-header-style.xml SLASHSTAR_CUSTOM_STYLE + + .github/FUNDING.yml + diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java index 8fbd80294b4c..e4dd0658a0d8 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -26,13 +26,10 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.Arrays; 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 static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.*; /** * Date: 12/28/15 - 8:45 PM @@ -41,7 +38,7 @@ */ public class PrototypeTest

{ static Collection dataProvider() { - return Arrays.asList( + return List.of( new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"}, new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"}, new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"}, diff --git a/proxy/README.md b/proxy/README.md index e0628344a931..71eba2280bf4 100644 --- a/proxy/README.md +++ b/proxy/README.md @@ -129,9 +129,6 @@ are several common situations in which the Proxy pattern is applicable ## Tutorials * [Controlling Access With Proxy Pattern](http://java-design-patterns.com/blog/controlling-access-with-proxy-pattern/) -## Presentations -* [Proxy](https://github.com/iluwatar/java-design-patterns/tree/master/proxy/etc/presentation.html) - ## Real world examples * [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html) diff --git a/proxy/etc/presentation.html b/proxy/etc/presentation.html deleted file mode 100644 index 20061c2c7bee..000000000000 --- a/proxy/etc/presentation.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - Title - - - - - - - - - diff --git a/proxy/etc/proxy-concept.png b/proxy/etc/proxy-concept.png deleted file mode 100644 index dac5d954bc58..000000000000 Binary files a/proxy/etc/proxy-concept.png and /dev/null differ diff --git a/proxy/etc/proxy-concept.xml b/proxy/etc/proxy-concept.xml deleted file mode 100644 index 14ade9c090eb..000000000000 --- a/proxy/etc/proxy-concept.xml +++ /dev/null @@ -1,25 +0,0 @@ - -7Vhtb5swEP41kbYPnQJuaPexeVv3YVK1aur60YEL8WowM05K+utnYxswkC6p2rSbmkoNfnx3vpfnLsAATZLiC8fZ6huLgA78YVQM0HTg+x4KPPmlkK1GziwQcxIZoRq4Jg9gwKFB1ySC3BEUjFFBMhcMWZpCKBwMc87uXbElo+6pGY6hA1yHmHbRGxKJlUbPR8MavwQSr+zJ3tDsLHB4F3O2Ts15Ax8ty4/eTrC1ZeTzFY7YfQNCswGacMaEvkqKCVCVW5s2rTffsVv5zSEV+yica4UNpmuwHgdUqo4z5Z3YmowEv9fKpXGCeUzSAbqQu8OskP8lWAam8BPBMr132tgTUIgTTEls9ELpG/DapryKzXd5MmkAOJEGx7S7+qpsLHEIFeyqOBZl/KR9yoJ3EAtcrxe/FKtq7UVbVmJZG1txlTLLZRudtzvQJ6WYwlI0crzLdje8PpdfxgMlW9b4ww15wDz6qKU3TLJuT/d8xzF/A1wQ2Z4XmkXTkmdjw6mpdmjMpNSSlt20JJLlaLxkqTDDxfPNeo4TQtVYugS6AWVVlU4kVAkpGak6YZTx8mTbvWicC87uoLEzLD+KahxHRMbb2Juezrz5qIpEuQ/Fzhb1qsaXAxVYAoJvpYhR8M/NrDCz1A6h+3owVeNk5Q4lMxDNMIwr0/VAkBdmJvTPB+vumxoQVTd+B0yP1awR2fQGbFOuHPcf68g8w+lBPSLddnUquPTl9VvlhYmPfJf4fcz3TnuYHzwH8f23TPwrzortO+X/O8oHnkv5s9ERGY/eIuN336VNqCrE/k3wj99SzAL19zw0G70iy7pPHLNCQBrlnQpJ8EI9y8nVgrLwTsYuIZv8QC/nZVmmQzfjMg98+1Phn0Z2eWv3CiIaW3J1awxoDyDqPBu28iq9ZGsegnuLJCTtQTQeq7rpbybYJpMDxYJs3CP7MmzMXTGiWL+jlAi1aqQ9NUrNB8GWHd/7iyEdXsdQWe8qxP0o8PmoFPCaBKiL/tOoVAQodw5v1SeSxn8nzUGkQd37sR85PEYYlkHq8kXN6wjnK4gMLZp0MZTwOpSoZ0mXSE8sPnov/mHF77s12V35lKVQ9izmomd8NOZFKWLWbULs8RPSJcvz/YToEI/CiKD1hqF643AsSsgi4W1DLFMC+eEO1wzTFvfkm1zWb1y1eP1aG83+AA== \ No newline at end of file diff --git a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java index 6e53713233a1..3b0bff608327 100644 --- a/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -23,16 +23,7 @@ package com.iluwatar.repository; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import javax.annotation.Resource; - +import com.google.common.collect.Lists; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,7 +31,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.google.common.collect.Lists; +import javax.annotation.Resource; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query @@ -59,7 +54,7 @@ public class AnnotationBasedRepositoryTest { Person john = new Person("John", "lawrence", 35); Person terry = new Person("Terry", "Law", 36); - List persons = Arrays.asList(peter, nasta, john, terry); + List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test diff --git a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java index 9f7615aa57de..614f18dba1af 100644 --- a/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java +++ b/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -23,16 +23,7 @@ package com.iluwatar.repository; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import javax.annotation.Resource; - +import com.google.common.collect.Lists; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,7 +31,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.google.common.collect.Lists; +import javax.annotation.Resource; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; /** * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query @@ -58,7 +53,7 @@ public class RepositoryTest { Person john = new Person("John", "lawrence", 35); Person terry = new Person("Terry", "Law", 36); - List persons = Arrays.asList(peter, nasta, john, terry); + List persons = List.of(peter, nasta, john, terry); /** * Prepare data for test diff --git a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java index 11c2b40d6e03..e5013f50e925 100644 --- a/retry/src/main/java/com/iluwatar/retry/FindCustomer.java +++ b/retry/src/main/java/com/iluwatar/retry/FindCustomer.java @@ -24,8 +24,8 @@ package com.iluwatar.retry; import java.util.ArrayDeque; -import java.util.Arrays; import java.util.Deque; +import java.util.List; /** * Finds a customer, returning its ID from our records. @@ -48,7 +48,7 @@ public final class FindCustomer implements BusinessOperation { */ public FindCustomer(String customerId, BusinessException... errors) { this.customerId = customerId; - this.errors = new ArrayDeque<>(Arrays.asList(errors)); + this.errors = new ArrayDeque<>(List.of(errors)); } @Override diff --git a/role-object/README.md b/role-object/README.md new file mode 100644 index 000000000000..0e960140c987 --- /dev/null +++ b/role-object/README.md @@ -0,0 +1,31 @@ +--- +layout: pattern +title: Role Object +folder: role-object +permalink: /patterns/role-object/ +categories: Structural +tags: + - Java + - Difficulty-Medium + - Handle Body Pattern +--- + +## Also known as +Post pattern, Extension Object pattern + +## Intent +Adapt an object to different client’s needs through transparently attached role objects, each one representing a role +the object has to play in that client’s context. The object manages its role set dynamically. By representing roles as +individual objects, different contexts are kept separate and system configuration is simplified. + +## Applicability +Use the Role Object pattern, if: +- you want to handle a key abstraction in different contexts and you do not want to put the resulting context specific interfaces into the same class interface. +- you want to handle the available roles dynamically so that they can be attached and removed on demand, that is at runtime, rather than fixing them statically at compile-time. +- you want to treat the extensions transparently and need to preserve the logical object identity of the resultingobject conglomerate. +- you want to keep role/client pairs independent from each other so that changes to a role do not affect clients that are not interested in that role. + +## Credits +- [Hillside - Role object pattern](https://hillside.net/plop/plop97/Proceedings/riehle.pdf) +- [Role object](http://wiki.c2.com/?RoleObject) +- [Fowler - Dealing with roles](https://martinfowler.com/apsupp/roles.pdf) \ No newline at end of file diff --git a/role-object/pom.xml b/role-object/pom.xml new file mode 100644 index 000000000000..c9feb1419afd --- /dev/null +++ b/role-object/pom.xml @@ -0,0 +1,44 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.22.0-SNAPSHOT + + + role-object + + + junit + junit + test + + + + diff --git a/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java new file mode 100644 index 000000000000..b8296dabacc6 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.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.roleobject; + +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 + * dynamically attached to and removed from the core object. + * We call the resulting composite object structure, + * consisting of the core and its role objects, a subject. + * A subject often plays several roles and the same role is likely to + * be played by different subjects. + * As an example consider two different customers playing the role of borrower and + * 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 + * 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. + * 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. + * 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); + + 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(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 new file mode 100644 index 000000000000..425d9511d083 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java @@ -0,0 +1,40 @@ +/* + * 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.roleobject; + +public class BorrowerRole extends CustomerRole{ + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = 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 new file mode 100644 index 000000000000..ebcddff4b154 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/Customer.java @@ -0,0 +1,79 @@ +/* + * 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.roleobject; + +import java.util.Optional; + +/** + * The main abstraction to work with Customer. + */ +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); + + /** + * Check specific role @see {@link Role} + * + * @param role to check + * @return true if the role exists otherwise false + */ + + 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); + + /** + * 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(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 new file mode 100644 index 000000000000..5de27aa9295d --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java @@ -0,0 +1,75 @@ +/* + * 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.roleobject; + +import java.util.*; + +/** + * Core class to store different customer roles + * + * @see CustomerRole + * Note: not thread safe + */ +public class CustomerCore extends Customer { + + private Map roles; + + 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 hasRole(Role role) { + return roles.containsKey(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 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 new file mode 100644 index 000000000000..40fe2341b3a9 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java @@ -0,0 +1,28 @@ +/* + * 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.roleobject; + +/** + * Key abstraction for segregated roles + */ +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 new file mode 100644 index 000000000000..6d5c17c904f7 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/InvestorRole.java @@ -0,0 +1,48 @@ +/* + * 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.roleobject; + +public class InvestorRole extends CustomerRole { + private String name; + private long amountToInvest; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getAmountToInvest() { + return amountToInvest; + } + + public void setAmountToInvest(long amountToInvest) { + this.amountToInvest = 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 new file mode 100644 index 000000000000..f6c739891566 --- /dev/null +++ b/role-object/src/main/java/com/iluwatar/roleobject/Role.java @@ -0,0 +1,55 @@ +/* + * 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.roleobject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +/** + * Possible roles + */ +public enum Role { + Borrower(BorrowerRole.class), Investor(InvestorRole.class); + + private Class typeCst; + + Role(Class typeCst) { + this.typeCst = typeCst; + } + + 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(); + } + +} diff --git a/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.java new file mode 100644 index 000000000000..831781d7103b --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/ApplicationRoleObjectTest.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.roleobject; + +import org.junit.Test; + +public class ApplicationRoleObjectTest { + + @Test + public void mainTest() { + ApplicationRoleObject.main(new String[]{}); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java new file mode 100644 index 000000000000..0c0f92fc2322 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/BorrowerRoleTest.java @@ -0,0 +1,40 @@ +/* + * 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.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class BorrowerRoleTest { + + @Test + public void borrowTest() { + BorrowerRole borrowerRole = new BorrowerRole(); + borrowerRole.setName("test"); + String res = "Borrower test wants to get some money."; + + Assert.assertEquals(borrowerRole.borrow(),res); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java new file mode 100644 index 000000000000..1b2987400d05 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/CustomerCoreTest.java @@ -0,0 +1,103 @@ +/* + * 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.roleobject; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.*; + +public class CustomerCoreTest { + + @Test + public void addRole() { + CustomerCore core = new CustomerCore(); + boolean add = core.addRole(Role.Borrower); + assertTrue(add); + + } + + @Test + public void hasRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + boolean has = core.hasRole(Role.Borrower); + assertTrue(has); + + boolean notHas = core.hasRole(Role.Investor); + assertFalse(notHas); + } + + @Test + public void remRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); + + boolean res = core.remRole(Role.Borrower); + assertTrue(res); + + Optional empt = core.getRole(Role.Borrower, BorrowerRole.class); + assertFalse(empt.isPresent()); + + } + + @Test + public void getRole() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + + Optional bRole = core.getRole(Role.Borrower, BorrowerRole.class); + assertTrue(bRole.isPresent()); + + Optional nonRole = core.getRole(Role.Borrower, InvestorRole.class); + assertFalse(nonRole.isPresent()); + + Optional invRole = core.getRole(Role.Investor, InvestorRole.class); + assertFalse(invRole.isPresent()); + + + } + + + @Test + public void toStringTest() { + CustomerCore core = new CustomerCore(); + core.addRole(Role.Borrower); + assertEquals(core.toString(), "Customer{roles=[Borrower]}"); + + core = new CustomerCore(); + core.addRole(Role.Investor); + assertEquals(core.toString(), "Customer{roles=[Investor]}"); + + core = new CustomerCore(); + assertEquals(core.toString(), "Customer{roles=[]}"); + + + } + +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java new file mode 100644 index 000000000000..06afa1016275 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/InvestorRoleTest.java @@ -0,0 +1,38 @@ +/* + * 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.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +public class InvestorRoleTest { + + @Test + public void investTest() { + InvestorRole investorRole = new InvestorRole(); + investorRole.setName("test"); + investorRole.setAmountToInvest(10); + String res = "Investor test has invested 10 dollars"; + Assert.assertEquals(investorRole.invest(), res); + } +} \ No newline at end of file diff --git a/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java new file mode 100644 index 000000000000..6ae5b0cd8857 --- /dev/null +++ b/role-object/src/test/java/com/iluwatar/roleobject/RoleTest.java @@ -0,0 +1,40 @@ +/* + * 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.roleobject; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.*; + +public class RoleTest { + + @Test + public void instanceTest() { + Optional instance = Role.Borrower.instance(); + Assert.assertTrue(instance.isPresent()); + Assert.assertEquals(instance.get().getClass(),BorrowerRole.class); + } +} \ No newline at end of file diff --git a/servant/src/main/java/com/iluwatar/servant/App.java b/servant/src/main/java/com/iluwatar/servant/App.java index a629856d5173..35a26dbcc955 100644 --- a/servant/src/main/java/com/iluwatar/servant/App.java +++ b/servant/src/main/java/com/iluwatar/servant/App.java @@ -26,7 +26,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.List; @@ -60,9 +59,7 @@ public static void scenario(Servant servant, int compliment) { King k = new King(); Queen q = new Queen(); - List guests = new ArrayList<>(); - guests.add(k); - guests.add(q); + List guests = List.of(k, q); // feed servant.feed(k); diff --git a/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/servant/src/test/java/com/iluwatar/servant/ServantTest.java index 4431f6d60837..02b69559e624 100644 --- a/servant/src/test/java/com/iluwatar/servant/ServantTest.java +++ b/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -25,7 +25,6 @@ import org.junit.jupiter.api.Test; -import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -76,15 +75,9 @@ public void testCheckIfYouWillBeHanged() { final Royalty badMoodRoyalty = mock(Royalty.class); when(badMoodRoyalty.getMood()).thenReturn(true); - final List goodCompany = new ArrayList<>(); - goodCompany.add(goodMoodRoyalty); - goodCompany.add(goodMoodRoyalty); - goodCompany.add(goodMoodRoyalty); + final List goodCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, goodMoodRoyalty); - final List badCompany = new ArrayList<>(); - goodCompany.add(goodMoodRoyalty); - goodCompany.add(goodMoodRoyalty); - goodCompany.add(badMoodRoyalty); + final List badCompany = List.of(goodMoodRoyalty, goodMoodRoyalty, badMoodRoyalty); assertTrue(new Servant("test").checkIfYouWillBeHanged(goodCompany)); assertTrue(new Servant("test").checkIfYouWillBeHanged(badCompany)); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java index 1da25e4cb51f..0e87e987b1f1 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/app/App.java @@ -79,24 +79,24 @@ public static void main(String[] args) { */ public static void initData() { // spells - Spell spell1 = new Spell("Ice dart"); - Spell spell2 = new Spell("Invisibility"); - Spell spell3 = new Spell("Stun bolt"); - Spell spell4 = new Spell("Confusion"); - Spell spell5 = new Spell("Darkness"); - Spell spell6 = new Spell("Fireball"); - Spell spell7 = new Spell("Enchant weapon"); - Spell spell8 = new Spell("Rock armour"); - Spell spell9 = new Spell("Light"); - Spell spell10 = new Spell("Bee swarm"); - Spell spell11 = new Spell("Haste"); - Spell spell12 = new Spell("Levitation"); - Spell spell13 = new Spell("Magic lock"); - Spell spell14 = new Spell("Summon hell bat"); - Spell spell15 = new Spell("Water walking"); - Spell spell16 = new Spell("Magic storm"); - Spell spell17 = new Spell("Entangle"); - SpellDao spellDao = new SpellDaoImpl(); + var spell1 = new Spell("Ice dart"); + var spell2 = new Spell("Invisibility"); + var spell3 = new Spell("Stun bolt"); + var spell4 = new Spell("Confusion"); + var spell5 = new Spell("Darkness"); + var spell6 = new Spell("Fireball"); + var spell7 = new Spell("Enchant weapon"); + var spell8 = new Spell("Rock armour"); + var spell9 = new Spell("Light"); + var spell10 = new Spell("Bee swarm"); + var spell11 = new Spell("Haste"); + var spell12 = new Spell("Levitation"); + var spell13 = new Spell("Magic lock"); + var spell14 = new Spell("Summon hell bat"); + var spell15 = new Spell("Water walking"); + var spell16 = new Spell("Magic storm"); + var spell17 = new Spell("Entangle"); + var spellDao = new SpellDaoImpl(); spellDao.persist(spell1); spellDao.persist(spell2); spellDao.persist(spell3); @@ -116,64 +116,64 @@ public static void initData() { spellDao.persist(spell17); // spellbooks - SpellbookDao spellbookDao = new SpellbookDaoImpl(); - Spellbook spellbook1 = new Spellbook("Book of Orgymon"); + var spellbookDao = new SpellbookDaoImpl(); + var spellbook1 = new Spellbook("Book of Orgymon"); spellbookDao.persist(spellbook1); spellbook1.addSpell(spell1); spellbook1.addSpell(spell2); spellbook1.addSpell(spell3); spellbook1.addSpell(spell4); spellbookDao.merge(spellbook1); - Spellbook spellbook2 = new Spellbook("Book of Aras"); + var spellbook2 = new Spellbook("Book of Aras"); spellbookDao.persist(spellbook2); spellbook2.addSpell(spell5); spellbook2.addSpell(spell6); spellbookDao.merge(spellbook2); - Spellbook spellbook3 = new Spellbook("Book of Kritior"); + var spellbook3 = new Spellbook("Book of Kritior"); spellbookDao.persist(spellbook3); spellbook3.addSpell(spell7); spellbook3.addSpell(spell8); spellbook3.addSpell(spell9); spellbookDao.merge(spellbook3); - Spellbook spellbook4 = new Spellbook("Book of Tamaex"); + var spellbook4 = new Spellbook("Book of Tamaex"); spellbookDao.persist(spellbook4); spellbook4.addSpell(spell10); spellbook4.addSpell(spell11); spellbook4.addSpell(spell12); spellbookDao.merge(spellbook4); - Spellbook spellbook5 = new Spellbook("Book of Idores"); + var spellbook5 = new Spellbook("Book of Idores"); spellbookDao.persist(spellbook5); spellbook5.addSpell(spell13); spellbookDao.merge(spellbook5); - Spellbook spellbook6 = new Spellbook("Book of Opaen"); + var spellbook6 = new Spellbook("Book of Opaen"); spellbookDao.persist(spellbook6); spellbook6.addSpell(spell14); spellbook6.addSpell(spell15); spellbookDao.merge(spellbook6); - Spellbook spellbook7 = new Spellbook("Book of Kihione"); + var spellbook7 = new Spellbook("Book of Kihione"); spellbookDao.persist(spellbook7); spellbook7.addSpell(spell16); spellbook7.addSpell(spell17); spellbookDao.merge(spellbook7); // wizards - WizardDao wizardDao = new WizardDaoImpl(); - Wizard wizard1 = new Wizard("Aderlard Boud"); + var wizardDao = new WizardDaoImpl(); + var wizard1 = new Wizard("Aderlard Boud"); wizardDao.persist(wizard1); wizard1.addSpellbook(spellbookDao.findByName("Book of Orgymon")); wizard1.addSpellbook(spellbookDao.findByName("Book of Aras")); wizardDao.merge(wizard1); - Wizard wizard2 = new Wizard("Anaxis Bajraktari"); + var wizard2 = new Wizard("Anaxis Bajraktari"); wizardDao.persist(wizard2); wizard2.addSpellbook(spellbookDao.findByName("Book of Kritior")); wizard2.addSpellbook(spellbookDao.findByName("Book of Tamaex")); wizardDao.merge(wizard2); - Wizard wizard3 = new Wizard("Xuban Munoa"); + var wizard3 = new Wizard("Xuban Munoa"); wizardDao.persist(wizard3); wizard3.addSpellbook(spellbookDao.findByName("Book of Idores")); wizard3.addSpellbook(spellbookDao.findByName("Book of Opaen")); wizardDao.merge(wizard3); - Wizard wizard4 = new Wizard("Blasius Dehooge"); + var wizard4 = new Wizard("Blasius Dehooge"); wizardDao.persist(wizard4); wizard4.addSpellbook(spellbookDao.findByName("Book of Kihione")); wizardDao.merge(wizard4); @@ -183,7 +183,7 @@ public static void initData() { * Query the data */ public static void queryData() { - MagicService service = + var service = new MagicServiceImpl(new WizardDaoImpl(), new SpellbookDaoImpl(), new SpellDaoImpl()); LOGGER.info("Enumerating all wizards"); for (Wizard w : service.findAllWizards()) { diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java index 9accede55349..8d93002e6795 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/common/DaoBaseImpl.java @@ -57,12 +57,12 @@ protected SessionFactory getSessionFactory() { @Override public E find(Long id) { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; E result = null; try { tx = session.beginTransaction(); - Criteria criteria = session.createCriteria(persistentClass); + var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.idEq(id)); result = (E) criteria.uniqueResult(); tx.commit(); @@ -79,7 +79,7 @@ public E find(Long id) { @Override public void persist(E entity) { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); @@ -97,7 +97,7 @@ public void persist(E entity) { @Override public E merge(E entity) { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; E result = null; try { @@ -117,7 +117,7 @@ public E merge(E entity) { @Override public void delete(E entity) { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); @@ -135,7 +135,7 @@ public void delete(E entity) { @Override public List findAll() { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; List result = null; try { diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java index 78bf3c0d00ce..cf8d35207fb2 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/magic/MagicServiceImpl.java @@ -70,14 +70,14 @@ public List findAllSpells() { @Override public List findWizardsWithSpellbook(String name) { - Spellbook spellbook = spellbookDao.findByName(name); + var spellbook = spellbookDao.findByName(name); return new ArrayList<>(spellbook.getWizards()); } @Override public List findWizardsWithSpell(String name) { - Spell spell = spellDao.findByName(name); - Spellbook spellbook = spell.getSpellbook(); + var spell = spellDao.findByName(name); + var spellbook = spell.getSpellbook(); return new ArrayList<>(spellbook.getWizards()); } } diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java index f4be0ae902ab..7a68d372bc19 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spell/SpellDaoImpl.java @@ -41,9 +41,9 @@ public class SpellDaoImpl extends DaoBaseImpl implements SpellDao { public Spell findByName(String name) { Transaction tx = null; Spell result = null; - try (Session session = getSessionFactory().openSession()) { + try (var session = getSessionFactory().openSession()) { tx = session.beginTransaction(); - Criteria criteria = session.createCriteria(persistentClass); + var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.eq("name", name)); result = (Spell) criteria.uniqueResult(); tx.commit(); diff --git a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java index 3ca708fde8f6..473cfaabd3f9 100644 --- a/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java +++ b/service-layer/src/main/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImpl.java @@ -39,12 +39,12 @@ public class SpellbookDaoImpl extends DaoBaseImpl implements Spellboo @Override public Spellbook findByName(String name) { - Session session = getSessionFactory().openSession(); + var session = getSessionFactory().openSession(); Transaction tx = null; Spellbook result = null; try { tx = session.beginTransaction(); - Criteria criteria = session.createCriteria(persistentClass); + var criteria = session.createCriteria(persistentClass); criteria.add(Restrictions.eq("name", name)); result = (Spellbook) criteria.uniqueResult(); result.getSpells().size(); diff --git a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java index 03284ab6ddd8..b4b3c5714ca3 100644 --- a/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java +++ b/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -97,11 +97,10 @@ public void testFindAllSpells() throws Exception { public void testFindWizardsWithSpellbook() throws Exception { final String bookname = "bookname"; final Spellbook spellbook = mock(Spellbook.class); - final Set wizards = new HashSet<>(); - wizards.add(mock(Wizard.class)); - wizards.add(mock(Wizard.class)); - wizards.add(mock(Wizard.class)); - + final Set wizards = Set.of( + mock(Wizard.class), + mock(Wizard.class), + mock(Wizard.class)); when(spellbook.getWizards()).thenReturn(wizards); final SpellbookDao spellbookDao = mock(SpellbookDao.class); @@ -126,11 +125,10 @@ public void testFindWizardsWithSpellbook() throws Exception { @Test public void testFindWizardsWithSpell() throws Exception { - final Set wizards = new HashSet<>(); - wizards.add(mock(Wizard.class)); - wizards.add(mock(Wizard.class)); - wizards.add(mock(Wizard.class)); - + final Set wizards = Set.of( + mock(Wizard.class), + mock(Wizard.class), + mock(Wizard.class)); final Spellbook spellbook = mock(Spellbook.class); when(spellbook.getWizards()).thenReturn(wizards); diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java index f5704c54f237..49d871ca9ca0 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/App.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/App.java @@ -45,7 +45,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - Service service = ServiceLocator.getService("jndi/serviceA"); + var service = ServiceLocator.getService("jndi/serviceA"); service.execute(); service = ServiceLocator.getService("jndi/serviceB"); service.execute(); diff --git a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java index a94d8289e39b..60f0f7c03fde 100644 --- a/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java +++ b/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.java @@ -45,7 +45,7 @@ private ServiceLocator() { * @return {@link Service} */ public static Service getService(String serviceJndiName) { - Service serviceObj = serviceCache.getService(serviceJndiName); + var serviceObj = serviceCache.getService(serviceJndiName); if (serviceObj != null) { return serviceObj; } else { @@ -53,7 +53,7 @@ public static Service getService(String serviceJndiName) { * If we are unable to retrive anything from cache, then lookup the service and add it in the * cache map */ - InitContext ctx = new InitContext(); + var ctx = new InitContext(); serviceObj = (Service) ctx.lookup(serviceJndiName); if (serviceObj != null) { // Only cache a service if it actually exists serviceCache.addService(serviceObj); diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java index 668e7658b65e..604b81184674 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/App.java +++ b/singleton/src/main/java/com/iluwatar/singleton/App.java @@ -27,40 +27,40 @@ import org.slf4j.LoggerFactory; /** - * Singleton pattern ensures that the class can have only one existing instance per Java classloader - * instance and provides global access to it. - *

- * One of the risks of this pattern is that bugs resulting from setting a singleton up in a + *

Singleton pattern ensures that the class can have only one existing instance per Java + * classloader instance and provides global access to it.

+ * + *

One of the risks of this pattern is that bugs resulting from setting a singleton up in a * distributed environment can be tricky to debug, since it will work fine if you debug with a * single classloader. Additionally, these problems can crop up a while after the implementation of * a singleton, since they may start out synchronous and only become async with time, so you it may - * not be clear why you are seeing certain changes in behaviour. - *

- * There are many ways to implement the Singleton. The first one is the eagerly initialized instance - * in {@link IvoryTower}. Eager initialization implies that the implementation is thread safe. If - * you can afford giving up control of the instantiation moment, then this implementation will suit - * you fine. - *

- * The other option to implement eagerly initialized Singleton is enum based Singleton. The example - * is found in {@link EnumIvoryTower}. At first glance the code looks short and simple. However, you - * should be aware of the downsides including committing to implementation strategy, extending the - * enum class, serializability and restrictions to coding. These are extensively discussed in Stack - * Overflow: + * not be clear why you are seeing certain changes in behaviour.

+ * + *

There are many ways to implement the Singleton. The first one is the eagerly initialized + * instance in {@link IvoryTower}. Eager initialization implies that the implementation is thread + * safe. If you can afford giving up control of the instantiation moment, then this implementation + * will suit you fine.

+ * + *

The other option to implement eagerly initialized Singleton is enum based Singleton. The + * example is found in {@link EnumIvoryTower}. At first glance the code looks short and simple. + * However, you should be aware of the downsides including committing to implementation strategy, + * extending the enum class, serializability and restrictions to coding. These are extensively + * discussed in Stack Overflow: * http://programmers.stackexchange.com/questions/179386/what-are-the-downsides-of-implementing - * -a-singleton-with-javas-enum - *

- * {@link ThreadSafeLazyLoadedIvoryTower} is a Singleton implementation that is initialized on + * -a-singleton-with-javas-enum

+ * + *

{@link ThreadSafeLazyLoadedIvoryTower} is a Singleton implementation that is initialized on * demand. The downside is that it is very slow to access since the whole access method is - * synchronized. - *

- * Another Singleton implementation that is initialized on demand is found in + * synchronized.

+ * + *

Another Singleton implementation that is initialized on demand is found in * {@link ThreadSafeDoubleCheckLocking}. It is somewhat faster than * {@link ThreadSafeLazyLoadedIvoryTower} since it doesn't synchronize the whole access method but - * only the method internals on specific conditions. - *

- * Yet another way to implement thread safe lazily initialized Singleton can be found in + * only the method internals on specific conditions.

+ * + *

Yet another way to implement thread safe lazily initialized Singleton can be found in * {@link InitializingOnDemandHolderIdiom}. However, this implementation requires at least Java 8 - * API level to work. + * API level to work.

*/ public class App { @@ -74,36 +74,36 @@ public class App { public static void main(String[] args) { // eagerly initialized singleton - IvoryTower ivoryTower1 = IvoryTower.getInstance(); - IvoryTower ivoryTower2 = IvoryTower.getInstance(); + var ivoryTower1 = IvoryTower.getInstance(); + var ivoryTower2 = IvoryTower.getInstance(); LOGGER.info("ivoryTower1={}", ivoryTower1); LOGGER.info("ivoryTower2={}", ivoryTower2); // lazily initialized singleton - ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower1 = + var threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower.getInstance(); - ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower2 = + var threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); // enum singleton - EnumIvoryTower enumIvoryTower1 = EnumIvoryTower.INSTANCE; - EnumIvoryTower enumIvoryTower2 = EnumIvoryTower.INSTANCE; + var enumIvoryTower1 = EnumIvoryTower.INSTANCE; + var enumIvoryTower2 = EnumIvoryTower.INSTANCE; LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); // double checked locking - ThreadSafeDoubleCheckLocking dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); + var dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl1.toString()); - ThreadSafeDoubleCheckLocking dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); + var dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl2.toString()); // initialize on demand holder idiom - InitializingOnDemandHolderIdiom demandHolderIdiom = + var demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom.toString()); - InitializingOnDemandHolderIdiom demandHolderIdiom2 = + var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom2.toString()); } diff --git a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java index 2028b7d76bd4..753201dba177 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/EnumIvoryTower.java @@ -24,10 +24,10 @@ package com.iluwatar.singleton; /** - * Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18 + *

Enum based singleton implementation. Effective Java 2nd Edition (Joshua Bloch) p. 18

* - * This implementation is thread safe, however adding any other method and its thread safety - * is developers responsibility. + *

This implementation is thread safe, however adding any other method and its thread safety + * is developers responsibility.

*/ public enum EnumIvoryTower { diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java index dfd4951f7726..205a7bd80bfc 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java +++ b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java @@ -24,16 +24,16 @@ package com.iluwatar.singleton; /** - * The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton - * object in Java. - *

- * The technique is as lazy as possible and works in all known versions of Java. It takes advantage - * of language guarantees about class initialization, and will therefore work correctly in all - * Java-compliant compilers and virtual machines. - *

- * The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than - * the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special - * language constructs (i.e. volatile or synchronized). + *

The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton + * object in Java.

+ * + *

The technique is as lazy as possible and works in all known versions of Java. It takes + * advantage of language guarantees about class initialization, and will therefore work correctly + * in all Java-compliant compilers and virtual machines.

+ * + *

The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) + * than the moment that getInstance() is called. Thus, this solution is thread-safe without + * requiring special language constructs (i.e. volatile or synchronized).

* */ public final class InitializingOnDemandHolderIdiom { @@ -41,9 +41,12 @@ public final class InitializingOnDemandHolderIdiom { /** * Private constructor. */ - private InitializingOnDemandHolderIdiom() {} + private InitializingOnDemandHolderIdiom() { + } /** + * Sigleton instance. + * * @return Singleton instance */ public static InitializingOnDemandHolderIdiom getInstance() { diff --git a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java index c8d551404c8b..0bc3af28b2f4 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/IvoryTower.java @@ -31,7 +31,8 @@ public final class IvoryTower { /** * Private constructor so nobody can instantiate the class. */ - private IvoryTower() {} + private IvoryTower() { + } /** * Static to class instance of the class. diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java index db285ce2f427..f5d47380f285 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java @@ -24,11 +24,11 @@ package com.iluwatar.singleton; /** - * Double check locking - *

- * http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html - *

- * Broken under Java 1.4. + *

Double check locking.

+ * + *

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

+ * + *

Broken under Java 1.4.

* * @author mortezaadi@gmail.com */ @@ -59,18 +59,22 @@ public static ThreadSafeDoubleCheckLocking getInstance() { // local variable increases performance by 25 percent // Joshua Bloch "Effective Java, Second Edition", p. 283-284 - ThreadSafeDoubleCheckLocking result = instance; - // Check if singleton instance is initialized. If it is initialized then we can return the instance. + var result = instance; + // Check if singleton instance is initialized. + // If it is initialized then we can return the instance. if (result == null) { - // It is not initialized but we cannot be sure because some other thread might have initialized it - // in the meanwhile. So to make sure we need to lock on an object to get mutual exclusion. + // It is not initialized but we cannot be sure because some other thread might have + // initialized it in the meanwhile. + // So to make sure we need to lock on an object to get mutual exclusion. synchronized (ThreadSafeDoubleCheckLocking.class) { - // Again assign the instance to local variable to check if it was initialized by some other thread - // while current thread was blocked to enter the locked zone. If it was initialized then we can - // return the previously created instance just like the previous null check. + // Again assign the instance to local variable to check if it was initialized by some + // other thread while current thread was blocked to enter the locked zone. + // If it was initialized then we can return the previously created instance + // just like the previous null check. result = instance; if (result == null) { - // The instance is still not initialized so we can safely (no other thread can enter this zone) + // The instance is still not initialized so we can safely + // (no other thread can enter this zone) // create an instance and make it our singleton instance. instance = result = new ThreadSafeDoubleCheckLocking(); } diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java index 82580acf6896..dd6d05fea433 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java @@ -24,11 +24,11 @@ package com.iluwatar.singleton; /** - * Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization - * mechanism. + *

Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization + * mechanism.

* - * Note: if created by reflection then a singleton will not be created but multiple options in the - * same classloader + *

Note: if created by reflection then a singleton will not be created but multiple options + * in the same classloader

*/ public final class ThreadSafeLazyLoadedIvoryTower { diff --git a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java index 66974e47271a..75043eae0bdc 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/AppTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.Test; /** - * - * Application test - * + * Application test. */ public class AppTest { diff --git a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java index 49dfae6b0d1b..6a19ca7526bc 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java @@ -24,14 +24,14 @@ package com.iluwatar.singleton; /** - * Date: 12/29/15 - 19:20 PM + * Date: 12/29/15 - 19:20 PM. * * @author Jeroen Meulemeester */ public class EnumIvoryTowerTest extends SingletonTest { /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. */ public EnumIvoryTowerTest() { super(() -> EnumIvoryTower.INSTANCE); diff --git a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java index d7021dac7bdd..e855550129f2 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java @@ -24,14 +24,15 @@ package com.iluwatar.singleton; /** - * Date: 12/29/15 - 19:22 PM + * Date: 12/29/15 - 19:22 PM. * * @author Jeroen Meulemeester */ -public class InitializingOnDemandHolderIdiomTest extends SingletonTest { +public class InitializingOnDemandHolderIdiomTest + extends SingletonTest { /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. */ public InitializingOnDemandHolderIdiomTest() { super(InitializingOnDemandHolderIdiom::getInstance); diff --git a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java index ac5a145cbedc..de4dc3a1814a 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java @@ -24,14 +24,14 @@ package com.iluwatar.singleton; /** - * Date: 12/29/15 - 19:23 PM + * Date: 12/29/15 - 19:23 PM. * * @author Jeroen Meulemeester */ public class IvoryTowerTest extends SingletonTest { /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. */ public IvoryTowerTest() { super(IvoryTower::getInstance); diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index e98796aefa5b..4dc1ecdff589 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -23,8 +23,10 @@ package com.iluwatar.singleton; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; import java.util.ArrayList; import java.util.List; @@ -34,19 +36,17 @@ import java.util.concurrent.Future; import java.util.function.Supplier; -import static java.time.Duration.ofMillis; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTimeout; +import org.junit.jupiter.api.Test; /** - * This class provides several test case that test singleton construction. + *

This class provides several test case that test singleton construction.

+ * + *

The first proves that multiple calls to the singleton getInstance object are the same when + * called in the SAME thread. The second proves that multiple calls to the singleton getInstance + * object are the same when called in the DIFFERENT thread.

* - * The first proves that multiple calls to the singleton getInstance object are the same when called - * in the SAME thread. The second proves that multiple calls to the singleton getInstance object are - * the same when called in the DIFFERENT thread. + *

Date: 12/29/15 - 19:25 PM

* - * Date: 12/29/15 - 19:25 PM * @param Supplier method generating singletons * @author Jeroen Meulemeester * @author Richard Jones @@ -54,12 +54,12 @@ public abstract class SingletonTest { /** - * The singleton's getInstance method + * The singleton's getInstance method. */ private final Supplier singletonInstanceMethod; /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. * * @param singletonInstanceMethod The singleton's getInstance method */ @@ -68,7 +68,7 @@ public SingletonTest(final Supplier singletonInstanceMethod) { } /** - * Test the singleton in a non-concurrent setting + * Test the singleton in a non-concurrent setting. */ @Test public void testMultipleCallsReturnTheSameObjectInSameThread() { @@ -83,7 +83,7 @@ public void testMultipleCallsReturnTheSameObjectInSameThread() { } /** - * Test singleton instance in a concurrent setting + * Test singleton instance in a concurrent setting. */ @Test public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java index fff516ad3a2e..8babb081e634 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java @@ -23,34 +23,35 @@ package com.iluwatar.singleton; -import org.junit.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; +import org.junit.Test; + /** - * Date: 12/29/15 - 19:26 PM + * Date: 12/29/15 - 19:26 PM. * * @author Jeroen Meulemeester */ public class ThreadSafeDoubleCheckLockingTest extends SingletonTest { /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeDoubleCheckLockingTest() { super(ThreadSafeDoubleCheckLocking::getInstance); } /** - * Test creating new instance by refection + * Test creating new instance by refection. */ @Test(expected = InvocationTargetException.class) public void testCreatingNewInstanceByRefection() throws Exception { ThreadSafeDoubleCheckLocking instance1 = ThreadSafeDoubleCheckLocking.getInstance(); Constructor constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor(); constructor.setAccessible(true); - ThreadSafeDoubleCheckLocking instance2 = (ThreadSafeDoubleCheckLocking) constructor.newInstance(null); + ThreadSafeDoubleCheckLocking instance2 = + (ThreadSafeDoubleCheckLocking) constructor.newInstance(null); } } \ No newline at end of file diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java index 7ca1caf3d695..da04722fc5e0 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTowerTest.java @@ -24,14 +24,15 @@ package com.iluwatar.singleton; /** - * Date: 12/29/15 - 19:26 PM + * Date: 12/29/15 - 19:26 PM. * * @author Jeroen Meulemeester */ -public class ThreadSafeLazyLoadedIvoryTowerTest extends SingletonTest { +public class ThreadSafeLazyLoadedIvoryTowerTest + extends SingletonTest { /** - * Create a new singleton test instance using the given 'getInstance' method + * Create a new singleton test instance using the given 'getInstance' method. */ public ThreadSafeLazyLoadedIvoryTowerTest() { super(ThreadSafeLazyLoadedIvoryTower::getInstance); diff --git a/specification/README.md b/specification/README.md index 564830653d7f..a72e253d7e9b 100644 --- a/specification/README.md +++ b/specification/README.md @@ -7,6 +7,7 @@ categories: Behavioral tags: - Java - Difficulty-Beginner + - Searching --- ## Also known as @@ -16,15 +17,78 @@ Filter, Criteria Specification pattern separates the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable for validation and for building to -order +order. ![alt text](./etc/specification.png "Specification") ## Applicability Use the Specification pattern when -* you need to select a subset of objects based on some criteria, and to refresh the selection at various times -* you need to check that only suitable objects are used for a certain role (validation) +* You need to select a subset of objects based on some criteria, and to refresh the selection at various times. +* You need to check that only suitable objects are used for a certain role (validation). + +## Explanation + +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. + +In Plain Words + +> Specification pattern allows us to separate the search criteria from the object that performs the search. + +Wikipedia says + +> In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using boolean logic. + +**Programmatic Example** + +If we look at our creature pool example from above, we have a set of creatures with certain properties. + +```java +public interface Creature { + String getName(); + Size getSize(); + Movement getMovement(); + Color getColor(); +} +``` + +And dragon implementation looks like this. + +```java +public class Dragon extends AbstractCreature { + + public Dragon() { + super("Dragon", Size.LARGE, Movement.FLYING, Color.RED); + } +} +``` + +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 { + + private final Movement movement; + + public MovementSelector(Movement m) { + this.movement = m; + } + + @Override + public boolean test(Creature t) { + return t.getMovement().equals(movement); + } +} +``` + +With these building blocks in place, we can perform a search for red and flying creatures like this. + +```java + List redAndFlyingCreatures = creatures.stream() + .filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))).collect(Collectors.toList()); +``` ## Related patterns 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 df80f855f1f5..8ca7283c9216 100644 --- a/specification/src/main/java/com/iluwatar/specification/app/App.java +++ b/specification/src/main/java/com/iluwatar/specification/app/App.java @@ -23,10 +23,6 @@ package com.iluwatar.specification.app; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.creature.Dragon; import com.iluwatar.specification.creature.Goblin; @@ -38,34 +34,33 @@ import com.iluwatar.specification.property.Movement; import com.iluwatar.specification.selector.ColorSelector; import com.iluwatar.specification.selector.MovementSelector; +import java.util.List; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * - * The central idea of the Specification pattern is to separate the statement of how to match a + *

The central idea of the Specification pattern is to separate the statement of how to match a * candidate, from the candidate object that it is matched against. As well as its usefulness in - * selection, it is also valuable for validation and for building to order. - *

- * In this example we have a pool of creatures with different properties. We then have defined + * selection, it is also valuable for validation and for building to order.

+ * + *

In this example we have a pool of creatures with different properties. We then have defined * separate selection rules (Specifications) that we apply to the collection and as output receive - * only the creatures that match the selection criteria. - *

- * http://martinfowler.com/apsupp/spec.pdf + * only the creatures that match the selection criteria.

* + *

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

*/ public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** - * Program entry point + * Program entry point. */ public static void main(String[] args) { // initialize creatures list - List creatures = - Arrays.asList(new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), - new KillerBee()); + List creatures = List.of(new Goblin(), new Octopus(), new Dragon(), new Shark(), + new Troll(), new KillerBee()); // find all walking creatures LOGGER.info("Find all walking creatures"); List walkingCreatures = 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 566885560c7e..de7a41417efa 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Base class for concrete creatures. - * */ public abstract class AbstractCreature implements Creature { @@ -40,7 +38,7 @@ public abstract class AbstractCreature implements Creature { private Color color; /** - * Constructor + * Constructor. */ public AbstractCreature(String name, Size size, Movement movement, Color color) { this.name = name; 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 c999f546d928..3f8ccdfdb259 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Creature.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Creature.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Creature interface. - * */ public interface Creature { 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 833b8522b866..d4f5a7f23164 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Dragon.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Dragon creature. - * */ public class Dragon extends AbstractCreature { 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 0153e21fe7e0..0b145b737b87 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Goblin.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Goblin creature. - * */ public class Goblin extends AbstractCreature { 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 04c416b7abe2..77f32c9f48ba 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/KillerBee.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * KillerBee creature. - * */ public class KillerBee extends AbstractCreature { 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 bb2c5718b8de..6958f7fbd658 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Octopus.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Octopus creature. - * */ public class Octopus extends AbstractCreature { 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 56ec1651aa4b..b9e161da43ee 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Shark.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Shark.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Shark creature. - * */ public class Shark extends AbstractCreature { 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 1d6a79bb8296..3f416bdd1ed3 100644 --- a/specification/src/main/java/com/iluwatar/specification/creature/Troll.java +++ b/specification/src/main/java/com/iluwatar/specification/creature/Troll.java @@ -28,9 +28,7 @@ import com.iluwatar.specification.property.Size; /** - * * Troll creature. - * */ public class Troll extends AbstractCreature { 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 9f64e1b77b2e..00f7007ff713 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Color.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Color.java @@ -24,9 +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/Movement.java b/specification/src/main/java/com/iluwatar/specification/property/Movement.java index 5bf0863e4ed2..f76b0584f35d 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Movement.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Movement.java @@ -24,9 +24,7 @@ package com.iluwatar.specification.property; /** - * * Movement property. - * */ public enum Movement { diff --git a/specification/src/main/java/com/iluwatar/specification/property/Size.java b/specification/src/main/java/com/iluwatar/specification/property/Size.java index a4a09e96c798..27bc48024fb9 100644 --- a/specification/src/main/java/com/iluwatar/specification/property/Size.java +++ b/specification/src/main/java/com/iluwatar/specification/property/Size.java @@ -24,9 +24,7 @@ package com.iluwatar.specification.property; /** - * * Size property. - * */ public enum Size { 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 75e922bff0ab..93caf612ff92 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/ColorSelector.java @@ -23,26 +23,23 @@ package com.iluwatar.specification.selector; -import java.util.function.Predicate; - import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Color; +import java.util.function.Predicate; /** - * * Color selector. - * */ public class ColorSelector implements Predicate { - private final Color c; + private final Color color; public ColorSelector(Color c) { - this.c = c; + this.color = c; } @Override public boolean test(Creature t) { - return t.getColor().equals(c); + return t.getColor().equals(color); } } 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 19613dfeddb7..1818058c15d8 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/MovementSelector.java @@ -23,26 +23,23 @@ package com.iluwatar.specification.selector; -import java.util.function.Predicate; - import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Movement; +import java.util.function.Predicate; /** - * * Movement selector. - * */ public class MovementSelector implements Predicate { - private final Movement m; + private final Movement movement; public MovementSelector(Movement m) { - this.m = m; + this.movement = m; } @Override public boolean test(Creature t) { - return t.getMovement().equals(m); + return t.getMovement().equals(movement); } } 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 1d561e95cff1..a997c034239d 100644 --- a/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java +++ b/specification/src/main/java/com/iluwatar/specification/selector/SizeSelector.java @@ -23,26 +23,23 @@ package com.iluwatar.specification.selector; -import java.util.function.Predicate; - import com.iluwatar.specification.creature.Creature; import com.iluwatar.specification.property.Size; +import java.util.function.Predicate; /** - * * Size selector. - * */ public class SizeSelector implements Predicate { - private final Size s; + private final Size size; public SizeSelector(Size s) { - this.s = s; + this.size = s; } @Override public boolean test(Creature t) { - return t.getSize().equals(s); + return t.getSize().equals(size); } } 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 022475c24238..26ff4c1ab877 100644 --- a/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java +++ b/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -29,8 +29,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -46,7 +46,7 @@ public class CreatureTest { * @return The tested {@link Creature} instance and its expected specs */ public static Collection dataProvider() { - return Arrays.asList( + 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}, @@ -76,15 +76,13 @@ 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 testToString(Creature testedCreature, String name, Size size, Movement movement, Color color) { final String toString = testedCreature.toString(); assertNotNull(toString); assertEquals( diff --git a/state/src/main/java/com/iluwatar/state/App.java b/state/src/main/java/com/iluwatar/state/App.java index d930e048bdda..86f0193287b1 100644 --- a/state/src/main/java/com/iluwatar/state/App.java +++ b/state/src/main/java/com/iluwatar/state/App.java @@ -41,7 +41,7 @@ public class App { */ public static void main(String[] args) { - Mammoth mammoth = new Mammoth(); + var mammoth = new Mammoth(); mammoth.observe(); mammoth.timePasses(); mammoth.observe(); diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java index dda5dd2258de..da301db6bbe3 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java @@ -69,20 +69,20 @@ public class App { */ public static void main(String[] args) { - Character warrior = + var warrior = CharacterStepBuilder.newBuilder().name("Amberjill").fighterClass("Paladin") .withWeapon("Sword").noAbilities().build(); LOGGER.info(warrior.toString()); - Character mage = + var mage = CharacterStepBuilder.newBuilder().name("Riobard").wizardClass("Sorcerer") .withSpell("Fireball").withAbility("Fire Aura").withAbility("Teleport") .noMoreAbilities().build(); LOGGER.info(mage.toString()); - Character thief = + var thief = CharacterStepBuilder.newBuilder().name("Desmond").fighterClass("Rogue").noWeapon().build(); LOGGER.info(thief.toString()); diff --git a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java index 5036bd3366b7..e643d19ff0d8 100644 --- a/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java +++ b/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java @@ -91,7 +91,7 @@ public void setAbilities(List abilities) { @Override public String toString() { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.append("This is a ") .append(fighterClass != null ? fighterClass : wizardClass) .append(" named ") diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java index 746afc0419dc..c526c791787d 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ b/strategy/src/main/java/com/iluwatar/strategy/App.java @@ -28,15 +28,15 @@ /** * - * The Strategy pattern (also known as the policy pattern) is a software design pattern that enables - * an algorithm's behavior to be selected at runtime. - *

- * Before Java 8 the Strategies needed to be separate classes forcing the developer + *

The Strategy pattern (also known as the policy pattern) is a software design pattern that + * enables an algorithm's behavior to be selected at runtime.

+ * + *

Before Java 8 the Strategies needed to be separate classes forcing the developer * to write lots of boilerplate code. With modern Java it is easy to pass behavior - * with method references and lambdas making the code shorter and more readable. - *

- * In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing object - * ({@link DragonSlayer}) can alter its behavior by changing its strategy. + * with method references and lambdas making the code shorter and more readable.

+ * + *

In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing + * object ({@link DragonSlayer}) can alter its behavior by changing its strategy.

* */ public class App { @@ -44,14 +44,14 @@ 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) { // GoF Strategy pattern LOGGER.info("Green dragon spotted ahead!"); - DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy()); + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); dragonSlayer.goToBattle(); LOGGER.info("Red dragon emerges."); dragonSlayer.changeStrategy(new ProjectileStrategy()); diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java index 0455edaca98b..f6b91d967aed 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java +++ b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java @@ -24,9 +24,7 @@ package com.iluwatar.strategy; /** - * * DragonSlayer uses different strategies to slay the dragon. - * */ public class DragonSlayer { diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java index eb89523ad402..537b521f4c4d 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java @@ -24,9 +24,7 @@ package com.iluwatar.strategy; /** - * * Strategy interface. - * */ @FunctionalInterface public interface DragonSlayingStrategy { diff --git a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java index 8cb2f24c12be..12f467b07330 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Melee strategy. - * */ public class MeleeStrategy implements DragonSlayingStrategy { diff --git a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java index 4b6031ddfa21..769b0d7d9815 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Projectile strategy. - * */ public class ProjectileStrategy implements DragonSlayingStrategy { diff --git a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java index ffe85c7a21f8..dfa47f72b215 100644 --- a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java +++ b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * * Spell strategy. - * */ public class SpellStrategy implements DragonSlayingStrategy { diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java index 598085ce4e03..713eecf43bdd 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.Test; /** - * - * Application test - * + * Application test. */ public class AppTest { diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java index 52dfb3ff19e9..c956126836b4 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -23,21 +23,21 @@ package com.iluwatar.strategy; -import org.junit.jupiter.api.Test; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import org.junit.jupiter.api.Test; + /** - * Date: 12/29/15 - 10:50 PM + * Date: 12/29/15 - 10:50 PM. * * @author Jeroen Meulemeester */ public class DragonSlayerTest { /** - * Verify if the dragon slayer uses the strategy during battle + * Verify if the dragon slayer uses the strategy during battle. */ @Test public void testGoToBattle() { @@ -50,7 +50,7 @@ public void testGoToBattle() { } /** - * Verify if the dragon slayer uses the new strategy during battle after a change of strategy + * Verify if the dragon slayer uses the new strategy during battle after a change of strategy. */ @Test public void testChangeStrategy() { diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java index b97cf499fbf8..15106cdd9f8d 100644 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -23,46 +23,48 @@ package com.iluwatar.strategy; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.LoggerFactory; /** - * Date: 12/29/15 - 10:58 PM + * Date: 12/29/15 - 10:58 PM. * * @author Jeroen Meulemeester */ public class DragonSlayingStrategyTest { /** + * Assembles test parameters. + * * @return The test parameters for each cycle */ static Collection dataProvider() { - return Arrays.asList( - new Object[]{ - new MeleeStrategy(), - "With your Excalibur you sever the dragon's head!" - }, - new Object[]{ - new ProjectileStrategy(), - "You shoot the dragon with the magical crossbow and it falls dead on the ground!" - }, - new Object[]{ - new SpellStrategy(), - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" - } + return List.of( + new Object[]{ + new MeleeStrategy(), + "With your Excalibur you sever the dragon's head!" + }, + new Object[]{ + new ProjectileStrategy(), + "You shoot the dragon with the magical crossbow and it falls dead on the ground!" + }, + new Object[]{ + new SpellStrategy(), + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" + } ); } @@ -80,7 +82,7 @@ public void tearDown() { /** - * Test if executing the strategy gives the correct response + * Test if executing the strategy gives the correct response. */ @ParameterizedTest @MethodSource("dataProvider") diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/App.java b/template-method/src/main/java/com/iluwatar/templatemethod/App.java index e9cc60118b67..8776b5ebc89f 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/App.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/App.java @@ -40,7 +40,7 @@ public class App { * @param args command line args */ public static void main(String[] args) { - HalflingThief thief = new HalflingThief(new HitAndRunMethod()); + var thief = new HalflingThief(new HitAndRunMethod()); thief.steal(); thief.changeMethod(new SubtleMethod()); thief.steal(); diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java index 02c91821d716..6ac898bcaad4 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java @@ -45,7 +45,7 @@ public abstract class StealingMethod { * Steal */ public void steal() { - String target = pickTarget(); + var target = pickTarget(); LOGGER.info("The target has been chosen as {}.", target); confuseTarget(target); stealTheItem(target); diff --git a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java index a4c1887d357d..b21f8cc4a1d3 100644 --- a/thread-pool/src/main/java/com/iluwatar/threadpool/App.java +++ b/thread-pool/src/main/java/com/iluwatar/threadpool/App.java @@ -60,34 +60,34 @@ public static void main(String[] args) { LOGGER.info("Program started"); // Create a list of tasks to be executed - List tasks = new ArrayList<>(); - tasks.add(new PotatoPeelingTask(3)); - tasks.add(new PotatoPeelingTask(6)); - tasks.add(new CoffeeMakingTask(2)); - tasks.add(new CoffeeMakingTask(6)); - tasks.add(new PotatoPeelingTask(4)); - tasks.add(new CoffeeMakingTask(2)); - tasks.add(new PotatoPeelingTask(4)); - tasks.add(new CoffeeMakingTask(9)); - tasks.add(new PotatoPeelingTask(3)); - tasks.add(new CoffeeMakingTask(2)); - tasks.add(new PotatoPeelingTask(4)); - tasks.add(new CoffeeMakingTask(2)); - tasks.add(new CoffeeMakingTask(7)); - tasks.add(new PotatoPeelingTask(4)); - tasks.add(new PotatoPeelingTask(5)); + List tasks = List.of( + new PotatoPeelingTask(3), + new PotatoPeelingTask(6), + new CoffeeMakingTask(2), + new CoffeeMakingTask(6), + new PotatoPeelingTask(4), + new CoffeeMakingTask(2), + new PotatoPeelingTask(4), + new CoffeeMakingTask(9), + new PotatoPeelingTask(3), + new CoffeeMakingTask(2), + new PotatoPeelingTask(4), + new CoffeeMakingTask(2), + new CoffeeMakingTask(7), + new PotatoPeelingTask(4), + new PotatoPeelingTask(5)); // Creates a thread pool that reuses a fixed number of threads operating off a shared // unbounded queue. At any point, at most nThreads threads will be active processing // tasks. If additional tasks are submitted when all threads are active, they will wait // in the queue until a thread is available. - ExecutorService executor = Executors.newFixedThreadPool(3); + var executor = Executors.newFixedThreadPool(3); // Allocate new worker for each task // The worker is executed when a thread becomes // available in the thread pool for (int i = 0; i < tasks.size(); i++) { - Runnable worker = new Worker(tasks.get(i)); + var worker = new Worker(tasks.get(i)); executor.execute(worker); } // All tasks were executed, now shutdown diff --git a/throttling/src/main/java/com/iluwatar/throttling/App.java b/throttling/src/main/java/com/iluwatar/throttling/App.java index a781763e981f..61674eb16329 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/App.java +++ b/throttling/src/main/java/com/iluwatar/throttling/App.java @@ -53,11 +53,11 @@ public class App { * @param args main arguments */ public static void main(String[] args) { - CallsCount callsCount = new CallsCount(); - Tenant adidas = new Tenant("Adidas", 5, callsCount); - Tenant nike = new Tenant("Nike", 6, callsCount); + var callsCount = new CallsCount(); + var adidas = new Tenant("Adidas", 5, callsCount); + var nike = new Tenant("Nike", 6, callsCount); - ExecutorService executorService = Executors.newFixedThreadPool(2); + var executorService = Executors.newFixedThreadPool(2); executorService.execute(() -> makeServiceCalls(adidas, callsCount)); executorService.execute(() -> makeServiceCalls(nike, callsCount)); @@ -74,8 +74,8 @@ public static void main(String[] args) { * Make calls to the B2BService dummy API */ private static void makeServiceCalls(Tenant tenant, CallsCount callsCount) { - Throttler timer = new ThrottleTimerImpl(10, callsCount); - B2BService service = new B2BService(timer, callsCount); + var timer = new ThrottleTimerImpl(10, callsCount); + var service = new B2BService(timer, callsCount); for (int i = 0; i < 20; i++) { service.dummyCustomerApi(tenant); // Sleep is introduced to keep the output in check and easy to view and analyze the results. diff --git a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java b/throttling/src/main/java/com/iluwatar/throttling/B2BService.java index a603d83fba0b..c00da6a3eb14 100644 --- a/throttling/src/main/java/com/iluwatar/throttling/B2BService.java +++ b/throttling/src/main/java/com/iluwatar/throttling/B2BService.java @@ -48,8 +48,8 @@ public B2BService(Throttler timer, CallsCount callsCount) { * @return customer id which is randomly generated */ public int dummyCustomerApi(Tenant tenant) { - String tenantName = tenant.getName(); - long count = callsCount.getCount(tenantName); + var tenantName = tenant.getName(); + var count = callsCount.getCount(tenantName); LOGGER.debug("Counter for {} : {} ", tenant.getName(), count); if (count >= tenant.getAllowedCallsPerSecond()) { LOGGER.error("API access per second limit reached for: {}", tenantName); diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java index 04ca5ffcce4f..2e69e2c7f2e9 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -23,8 +23,10 @@ package com.iluwatar.tls; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -32,9 +34,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -82,7 +81,7 @@ public class DateFormatCallableTest { /** * Expected content of the list containing the date values created by the run of DateFormatRunnalbe */ - List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + List expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); /** * Run Callable and prepare results for usage in the test methods diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java index 2c88fc13d9e0..df2ab2a93419 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -23,16 +23,15 @@ package com.iluwatar.tls; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -76,7 +75,7 @@ public class DateFormatCallableTestIncorrectDateFormat { /** * Expected content of the list containing the exceptions created by the run of DateFormatRunnalbe */ - List expectedExceptions = Arrays.asList("class java.text.ParseException: Unparseable date: \"15.12.2015\"", + List expectedExceptions = List.of("class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", "class java.text.ParseException: Unparseable date: \"15.12.2015\"", diff --git a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java index 11e8eef5bc2a..1001e1bdf59b 100644 --- a/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java +++ b/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -23,8 +23,10 @@ package com.iluwatar.tls; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -32,9 +34,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -86,7 +85,7 @@ static class StringArrayList extends ArrayList { /** * Expected content of the list containing the date values created by each thread */ - List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + List expectedDateValues = List.of("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); /** * Run Callable and prepare results for usage in the test methods diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java index 12afe83ad0e6..37ab2c2afbda 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java @@ -52,24 +52,24 @@ public class App { */ public static void main(String[] args) throws IOException, ClassNotFoundException { // Write V1 - RainbowFish fishV1 = new RainbowFish("Zed", 10, 11, 12); + var fishV1 = new RainbowFish("Zed", 10, 11, 12); LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons()); RainbowFishSerializer.writeV1(fishV1, "fish1.out"); // Read V1 - RainbowFish deserializedFishV1 = RainbowFishSerializer.readV1("fish1.out"); + var deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out"); LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", - deserializedFishV1.getName(), deserializedFishV1.getAge(), - deserializedFishV1.getLengthMeters(), deserializedFishV1.getWeightTons()); + deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(), + deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons()); // Write V2 - RainbowFishV2 fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); + var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); LOGGER.info( "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), fishV2.getHungry(), fishV2.getAngry(), fishV2.getSleeping()); RainbowFishSerializer.writeV2(fishV2, "fish2.out"); // Read V2 with V1 method - RainbowFish deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); + var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", deserializedFishV2.getName(), deserializedFishV2.getAge(), deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons()); diff --git a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java index a3dcae5e4b5f..3e8db7622101 100644 --- a/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java +++ b/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java @@ -48,13 +48,15 @@ private RainbowFishSerializer() { * Write V1 RainbowFish to file */ public static void writeV1(RainbowFish rainbowFish, String filename) throws IOException { - Map map = new HashMap<>(); - map.put("name", rainbowFish.getName()); - map.put("age", String.format("%d", rainbowFish.getAge())); - map.put("lengthMeters", String.format("%d", rainbowFish.getLengthMeters())); - map.put("weightTons", String.format("%d", rainbowFish.getWeightTons())); - try (FileOutputStream fileOut = new FileOutputStream(filename); - ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) { + var map = Map.of( + "name", rainbowFish.getName(), + "age", String.format("%d", rainbowFish.getAge()), + "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()), + "weightTons", String.format("%d", rainbowFish.getWeightTons()) + ); + + try (var fileOut = new FileOutputStream(filename); + var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } @@ -63,16 +65,18 @@ public static void writeV1(RainbowFish rainbowFish, String filename) throws IOEx * Write V2 RainbowFish to file */ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException { - Map map = new HashMap<>(); - map.put("name", rainbowFish.getName()); - map.put("age", String.format("%d", rainbowFish.getAge())); - map.put("lengthMeters", String.format("%d", rainbowFish.getLengthMeters())); - map.put("weightTons", String.format("%d", rainbowFish.getWeightTons())); - map.put("angry", Boolean.toString(rainbowFish.getAngry())); - map.put("hungry", Boolean.toString(rainbowFish.getHungry())); - map.put("sleeping", Boolean.toString(rainbowFish.getSleeping())); - try (FileOutputStream fileOut = new FileOutputStream(filename); - ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) { + var map = Map.of( + "name", rainbowFish.getName(), + "age", String.format("%d", rainbowFish.getAge()), + "lengthMeters", String.format("%d", rainbowFish.getLengthMeters()), + "weightTons", String.format("%d", rainbowFish.getWeightTons()), + "angry", Boolean.toString(rainbowFish.getAngry()), + "hungry", Boolean.toString(rainbowFish.getHungry()), + "sleeping", Boolean.toString(rainbowFish.getSleeping()) + ); + + try (var fileOut = new FileOutputStream(filename); + var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } @@ -83,8 +87,8 @@ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IO public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException { Map map = null; - try (FileInputStream fileIn = new FileInputStream(filename); - ObjectInputStream objIn = new ObjectInputStream(fileIn)) { + try (var fileIn = new FileInputStream(filename); + var objIn = new ObjectInputStream(fileIn)) { map = (Map) objIn.readObject(); } diff --git a/twin/src/main/java/com/iluwatar/twin/App.java b/twin/src/main/java/com/iluwatar/twin/App.java index 50f21426841c..6e6ce6ab7af0 100644 --- a/twin/src/main/java/com/iluwatar/twin/App.java +++ b/twin/src/main/java/com/iluwatar/twin/App.java @@ -41,8 +41,8 @@ public class App { */ public static void main(String[] args) throws Exception { - BallItem ballItem = new BallItem(); - BallThread ballThread = new BallThread(); + var ballItem = new BallItem(); + var ballThread = new BallThread(); ballItem.setTwin(ballThread); ballThread.setTwin(ballItem); diff --git a/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java index 77ce539c367b..6febfcacff9c 100644 --- a/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java +++ b/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java @@ -39,7 +39,7 @@ public static void main(String[] args) { var shyam = new Student(2, "Shyam", "Z bridge, Pune"); var gopi = new Student(3, "Gopi", "Street 10, Mumbai"); - HashMap> context = new HashMap<>(); + var context = new HashMap>(); var studentDatabase = new StudentDatabase(); var studentRepository = new StudentRepository(context, studentDatabase); diff --git a/update-ghpages.sh b/update-website.sh similarity index 75% rename from update-ghpages.sh rename to update-website.sh index 25ea680cc906..66192f15f82a 100644 --- a/update-ghpages.sh +++ b/update-website.sh @@ -24,22 +24,23 @@ # Clone gh-pages -git clone -b gh-pages "https://${GH_REF}" ghpagesclone -cd ghpagesclone +git clone https://github.com/iluwatar/java-design-patterns-web.git +cd java-design-patterns-web # Init and update submodule to latest git submodule update --init --recursive -git submodule update --remote +cd 30-seconds-of-java +git pull origin master +cd ../patterns +git pull origin master +cd ../programming-principles +git pull origin gh-pages +cd .. # Setup Git git config user.name "Travis-CI" git config user.email "travis@no.reply" -# If there is a new version of the master branch -if git status | grep patterns > /dev/null 2>&1 -then - # it should be committed - git add . - git commit -m ":sparkles: :up: Automagic Update via Travis-CI" - git push --quiet "https://${GH_TOKEN}:x-oauth-basic@${GH_REF}" gh-pages > /dev/null 2>&1 -fi +git add . +git commit -m ":sparkles: :up: Automagic Update via Travis-CI" +git push --quiet "https://${GH_TOKEN}:x-oauth-basic@github.com/iluwatar/java-design-patterns-web.git" master > /dev/null 2>&1 diff --git a/visitor/src/main/java/com/iluwatar/visitor/App.java b/visitor/src/main/java/com/iluwatar/visitor/App.java index 7b33f7e4d6c4..7f0abb0f0f3b 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/App.java +++ b/visitor/src/main/java/com/iluwatar/visitor/App.java @@ -24,19 +24,18 @@ package com.iluwatar.visitor; /** - * - * Visitor pattern defines mechanism to apply operations on nodes in hierarchy. New operations can - * be added without altering the node interface. - *

- * In this example there is a unit hierarchy beginning from {@link Commander}. This hierarchy is + *

Visitor pattern defines mechanism to apply operations on nodes in hierarchy. New operations + * can be added without altering the node interface.

+ * + *

In this example there is a unit hierarchy beginning from {@link Commander}. This hierarchy is * traversed by visitors. {@link SoldierVisitor} applies its operation on {@link Soldier}s, - * {@link SergeantVisitor} on {@link Sergeant}s and so on. + * {@link SergeantVisitor} on {@link Sergeant}s and so on.

* */ public class App { /** - * Program entry point + * Program entry point. * * @param args command line args */ diff --git a/visitor/src/main/java/com/iluwatar/visitor/Commander.java b/visitor/src/main/java/com/iluwatar/visitor/Commander.java index 938c42f8d0a2..782d0116c650 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Commander.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Commander.java @@ -24,9 +24,7 @@ package com.iluwatar.visitor; /** - * - * Commander - * + * Commander. */ public class Commander extends Unit { diff --git a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java index 19ea5846ecc5..c34c8ed9e36b 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/CommanderVisitor.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * CommanderVisitor - * + * CommanderVisitor. */ public class CommanderVisitor implements UnitVisitor { diff --git a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java index 95de257729aa..bdc96892ac89 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Sergeant.java @@ -24,9 +24,7 @@ package com.iluwatar.visitor; /** - * - * Sergeant - * + * Sergeant. */ public class Sergeant extends Unit { diff --git a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java index fdcdce5cad28..59fb405e58a9 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SergeantVisitor.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * SergeantVisitor - * + * SergeantVisitor. */ public class SergeantVisitor implements UnitVisitor { diff --git a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java index 7ab4a26b96be..a2a812416040 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Soldier.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Soldier.java @@ -24,9 +24,7 @@ package com.iluwatar.visitor; /** - * - * Soldier - * + * Soldier. */ public class Soldier extends Unit { diff --git a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java index 6585246a0673..1f19a6458f5e 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/SoldierVisitor.java @@ -27,9 +27,7 @@ import org.slf4j.LoggerFactory; /** - * - * SoldierVisitor - * + * SoldierVisitor. */ public class SoldierVisitor implements UnitVisitor { diff --git a/visitor/src/main/java/com/iluwatar/visitor/Unit.java b/visitor/src/main/java/com/iluwatar/visitor/Unit.java index 49ddb8a899d4..318e84262f7a 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/Unit.java +++ b/visitor/src/main/java/com/iluwatar/visitor/Unit.java @@ -24,9 +24,7 @@ package com.iluwatar.visitor; /** - * * Interface for the nodes in hierarchy. - * */ public abstract class Unit { @@ -37,7 +35,7 @@ public Unit(Unit... children) { } /** - * Accept visitor + * Accept visitor. */ public void accept(UnitVisitor visitor) { for (var child : children) { diff --git a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java index 086075e5e24d..8300fd1fe381 100644 --- a/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java +++ b/visitor/src/main/java/com/iluwatar/visitor/UnitVisitor.java @@ -24,9 +24,7 @@ package com.iluwatar.visitor; /** - * * Visitor interface. - * */ public interface UnitVisitor { diff --git a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java index fb2fdd1233bc..45804a9c6f48 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/AppTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.Test; /** - * - * Application test - * + * Application test. */ public class AppTest { diff --git a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java index f3cf823fce5d..256a0cdbdd39 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/CommanderTest.java @@ -27,14 +27,14 @@ import static org.mockito.Mockito.verify; /** - * Date: 12/30/15 - 19:45 PM + * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ public class CommanderTest extends UnitTest { /** - * Create a new test instance for the given {@link Commander} + * Create a new test instance for the given {@link Commander}. */ public CommanderTest() { super(Commander::new); diff --git a/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java index ed46ac90a592..935baa58d4fb 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/CommanderVisitorTest.java @@ -26,14 +26,14 @@ import java.util.Optional; /** - * Date: 12/30/15 - 18:43 PM + * Date: 12/30/15 - 18:43 PM. * * @author Jeroen Meulemeester */ public class CommanderVisitorTest extends VisitorTest { /** - * Create a new test instance for the given visitor + * Create a new test instance for the given visitor. */ public CommanderVisitorTest() { super( diff --git a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java index b2e3d5baf68e..fd977f2bc439 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SergeantTest.java @@ -27,14 +27,14 @@ import static org.mockito.Mockito.verify; /** - * Date: 12/30/15 - 19:45 PM + * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ public class SergeantTest extends UnitTest { /** - * Create a new test instance for the given {@link Sergeant} + * Create a new test instance for the given {@link Sergeant}. */ public SergeantTest() { super(Sergeant::new); diff --git a/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java index f7595b429003..05eae49f22f9 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SergeantVisitorTest.java @@ -26,14 +26,14 @@ import java.util.Optional; /** - * Date: 12/30/15 - 18:36 PM + * Date: 12/30/15 - 18:36 PM. * * @author Jeroen Meulemeester */ public class SergeantVisitorTest extends VisitorTest { /** - * Create a new test instance for the given visitor + * Create a new test instance for the given visitor. */ public SergeantVisitorTest() { super( diff --git a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java index 713b190e2d5e..3d2c7698f439 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SoldierTest.java @@ -27,14 +27,14 @@ import static org.mockito.Mockito.verify; /** - * Date: 12/30/15 - 19:45 PM + * Date: 12/30/15 - 19:45 PM. * * @author Jeroen Meulemeester */ public class SoldierTest extends UnitTest { /** - * Create a new test instance for the given {@link Soldier} + * Create a new test instance for the given {@link Soldier}. */ public SoldierTest() { super(Soldier::new); diff --git a/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java index e5572f1ee8c9..653d814c5878 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/SoldierVisitorTest.java @@ -26,14 +26,14 @@ import java.util.Optional; /** - * Date: 12/30/15 - 18:59 PM + * Date: 12/30/15 - 18:59 PM. * * @author Jeroen Meulemeester */ public class SoldierVisitorTest extends VisitorTest { /** - * Create a new test instance for the given visitor + * Create a new test instance for the given visitor. */ public SoldierVisitorTest() { super( diff --git a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java index 4441570d4dfb..7385ea5a7bd3 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -23,18 +23,18 @@ package com.iluwatar.visitor; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.function.Function; - import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import java.util.Arrays; +import java.util.function.Function; + +import org.junit.jupiter.api.Test; + /** - * Date: 12/30/15 - 18:59 PM + * Date: 12/30/15 - 18:59 PM. * Test related to Units * @param Type of Unit * @author Jeroen Meulemeester @@ -42,12 +42,12 @@ public abstract class UnitTest { /** - * Factory to create new instances of the tested unit + * Factory to create new instances of the tested unit. */ private final Function factory; /** - * Create a new test instance for the given unit type {@link U} + * Create a new test instance for the given unit type {@link U}. * * @param factory Factory to create new instances of the tested unit */ @@ -74,7 +74,7 @@ public void testAccept() { } /** - * Verify if the correct visit method is called on the mock, depending on the tested instance + * Verify if the correct visit method is called on the mock, depending on the tested instance. * * @param unit The tested unit instance * @param mockedVisitor The mocked {@link UnitVisitor} who should have gotten a visit by the unit diff --git a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java index c50c3822d284..3c458f6f4c85 100644 --- a/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java +++ b/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -23,6 +23,8 @@ package com.iluwatar.visitor; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; @@ -35,10 +37,8 @@ import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.assertEquals; - /** - * Date: 12/30/15 - 18:59 PM + * Date: 12/30/15 - 18:59 PM. * Test case for Visitor Pattern * @param Type of UnitVisitor * @author Jeroen Meulemeester @@ -58,34 +58,36 @@ public void tearDown() { } /** - * The tested visitor instance + * The tested visitor instance. */ private final V visitor; /** - * The optional expected response when being visited by a commander + * The optional expected response when being visited by a commander. */ private final Optional commanderResponse; /** - * The optional expected response when being visited by a sergeant + * The optional expected response when being visited by a sergeant. */ private final Optional sergeantResponse; /** - * The optional expected response when being visited by a soldier + * The optional expected response when being visited by a soldier. */ private final Optional soldierResponse; /** - * Create a new test instance for the given visitor + * Create a new test instance for the given visitor. * * @param commanderResponse The optional expected response when being visited by a commander * @param sergeantResponse The optional expected response when being visited by a sergeant * @param soldierResponse The optional expected response when being visited by a soldier */ - public VisitorTest(final V visitor, final Optional commanderResponse, - final Optional sergeantResponse, final Optional soldierResponse) { + public VisitorTest(final V visitor, + final Optional commanderResponse, + final Optional sergeantResponse, + final Optional soldierResponse) { this.visitor = visitor; this.commanderResponse = commanderResponse;