diff --git a/abstract-factory/README.md b/abstract-factory/README.md index 842e887994a0..2d18e25d2af1 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -30,6 +30,8 @@ Wikipedia says > The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes +![alt text](./etc/677px-Abstract_factory_UML.svg.png "Abstract Factory ") + **Programmatic Example** Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the kingdom diff --git a/abstract-factory/etc/677px-Abstract_factory_UML.svg.png b/abstract-factory/etc/677px-Abstract_factory_UML.svg.png new file mode 100644 index 000000000000..07bf45605a54 Binary files /dev/null and b/abstract-factory/etc/677px-Abstract_factory_UML.svg.png differ diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java index 4d6043abc007..644351cbdd7a 100644 --- a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/App.java @@ -25,7 +25,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; /** * @@ -95,32 +94,7 @@ private void setArmy(final Army army) { this.army = army; } - /** - * The factory of kingdom factories. - */ - public static class FactoryMaker { - - /** - * Enumeration for the different types of Kingdoms. - */ - public enum KingdomType { - ELF, ORC - } - - /** - * The factory method to create KingdomFactory concrete objects. - */ - public static KingdomFactory makeFactory(KingdomType type) { - switch (type) { - case ELF: - return new ElfKingdomFactory(); - case ORC: - return new OrcKingdomFactory(); - default: - throw new IllegalArgumentException("KingdomType not supported."); - } - } - } + /** * Program entry point. diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/FactoryMaker.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/FactoryMaker.java new file mode 100644 index 000000000000..a619e5885826 --- /dev/null +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/FactoryMaker.java @@ -0,0 +1,19 @@ +package com.iluwatar.abstractfactory; + +public class FactoryMaker { + + + /** + * The factory method to create KingdomFactory concrete objects. + */ + public static KingdomFactory makeFactory(KingdomType type) { + switch (type) { + case ELF: + return new ElfKingdomFactory(); + case ORC: + return new OrcKingdomFactory(); + default: + throw new IllegalArgumentException("KingdomType not supported."); + } + } +} \ No newline at end of file diff --git a/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomType.java b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomType.java new file mode 100644 index 000000000000..a250673aa073 --- /dev/null +++ b/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomType.java @@ -0,0 +1,5 @@ +package com.iluwatar.abstractfactory; + +public enum KingdomType { + ELF, ORC +} diff --git a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java index 7613edf65fb8..200ded1d8422 100644 --- a/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java +++ b/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -51,6 +51,7 @@ public void king() { final King elfKing = app.getKing(elfFactory); assertTrue(elfKing instanceof ElfKing); assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); + final King orcKing = app.getKing(orcFactory); assertTrue(orcKing instanceof OrcKing); assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); @@ -61,6 +62,7 @@ public void castle() { final Castle elfCastle = app.getCastle(elfFactory); assertTrue(elfCastle instanceof ElfCastle); assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); + final Castle orcCastle = app.getCastle(orcFactory); assertTrue(orcCastle instanceof OrcCastle); assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); @@ -71,6 +73,7 @@ public void army() { final Army elfArmy = app.getArmy(elfFactory); assertTrue(elfArmy instanceof ElfArmy); assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); + final Army orcArmy = app.getArmy(orcFactory); assertTrue(orcArmy instanceof OrcArmy); assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); diff --git a/adapter/README.md b/adapter/README.md index 3344490ff9a2..d0c1ca6f77dd 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -34,69 +34,7 @@ Wikipedia says > In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. -**Programmatic Example** -Consider a captain that can only use rowing boats and cannot sail at all. - -First we have interfaces `RowingBoat` and `FishingBoat` - -``` -public interface RowingBoat { - void row(); -} - -public class FishingBoat { - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); - public void sail() { - LOGGER.info("The fishing boat is sailing"); - } -} -``` - -And captain expects an implementation of `RowingBoat` interface to be able to move - -``` -public class Captain implements RowingBoat { - - private RowingBoat rowingBoat; - - public Captain(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } - - @Override - public void row() { - rowingBoat.row(); - } -} -``` - -Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills. - -``` -public class FishingBoatAdapter implements RowingBoat { - - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class); - - private FishingBoat boat; - - public FishingBoatAdapter() { - boat = new FishingBoat(); - } - - @Override - public void row() { - boat.sail(); - } -} -``` - -And now the `Captain` can use the `FishingBoat` to escape the pirates. - -``` -Captain captain = new Captain(new FishingBoatAdapter()); -captain.row(); -``` ## Applicability Use the Adapter pattern when diff --git a/adapter/src/main/java/com/iluwatar/adapter/Captain.java b/adapter/src/main/java/com/iluwatar/adapter/Captain.java deleted file mode 100644 index 3690169800d2..000000000000 --- a/adapter/src/main/java/com/iluwatar/adapter/Captain.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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; - -/** - * The Captain uses {@link RowingBoat} to sail.
- * This is the client in the pattern. - */ -public class Captain implements RowingBoat { - - private RowingBoat rowingBoat; - - public Captain() {} - - public Captain(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } - - public void setRowingBoat(RowingBoat rowingBoat) { - this.rowingBoat = rowingBoat; - } - - @Override - public void row() { - rowingBoat.row(); - } - -} diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java deleted file mode 100644 index 1e758e917040..000000000000 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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; - -/** - * - * 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 { - - private FishingBoat boat; - - public FishingBoatAdapter() { - boat = new FishingBoat(); - } - - @Override - public void row() { - boat.sail(); - } -} diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/own/App.java similarity index 73% rename from adapter/src/main/java/com/iluwatar/adapter/App.java rename to adapter/src/main/java/com/iluwatar/own/App.java index a624cc38f264..802a03b0cba5 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/own/App.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.adapter; +package com.iluwatar.own; /** * An adapter helps two incompatible interfaces to work together. This is the real world definition @@ -34,15 +34,15 @@ * 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 MuhasebeciAdapter}) converts the interface of the adaptee class ( + * {@link VergilendirmeIslemleri}) into a suitable one expected by the client ( {@link MuhasebeYapabilme} ). * *

* 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 MuhasebeYapabilme} to flee! We have a {@link VergilendirmeIslemleri} and our + * captain. We have no time to make up a new ship! we need to reuse this {@link VergilendirmeIslemleri}. The + * captain needs a rowing boat which he can operate. The spec is in {@link MuhasebeYapabilme}. We will + * use the Adapter pattern to reuse {@link VergilendirmeIslemleri}. * */ public class App { @@ -53,8 +53,9 @@ public class App { * @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 - Captain captain = new Captain(new FishingBoatAdapter()); - captain.row(); + // Bilgisayar Muhendisi adapter sayesinde artık muhasebe islemleri yapabiliyor. + BilgisayarMuhendisi bilgisayarMuhendisi = new BilgisayarMuhendisi(); + bilgisayarMuhendisi.setMuhasebeYapabilme(new MuhasebeciAdapter()); + bilgisayarMuhendisi.muhasebeIsiYap(); } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/adapter/src/main/java/com/iluwatar/own/BilgisayarMuhendisi.java similarity index 66% rename from decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java rename to adapter/src/main/java/com/iluwatar/own/BilgisayarMuhendisi.java index edaa334a5976..201a9eebe7a8 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java +++ b/adapter/src/main/java/com/iluwatar/own/BilgisayarMuhendisi.java @@ -20,37 +20,33 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.decorator; +package com.iluwatar.own; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Decorator that adds a club for the troll + * The BilgisayarMuhendisi uses {@link MuhasebeYapabilme}
+ * This is the client in the pattern. */ -public class ClubbedTroll implements Troll { +public class BilgisayarMuhendisi implements MuhasebeYapabilme { - private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BilgisayarMuhendisi.class); - private Troll decorated; + private MuhasebeYapabilme muhasebeYapabilme; - public ClubbedTroll(Troll decorated) { - this.decorated = decorated; + public BilgisayarMuhendisi() { + LOGGER.info("Muhasebe islemlerinden nefret ederim"); } - @Override - public void attack() { - decorated.attack(); - LOGGER.info("The troll swings at you with a club!"); - } - @Override - public int getAttackPower() { - return decorated.getAttackPower() + 10; + public void setMuhasebeYapabilme(MuhasebeYapabilme muhasebeYapabilme) { + this.muhasebeYapabilme = muhasebeYapabilme; } @Override - public void fleeBattle() { - decorated.fleeBattle(); + public void muhasebeIsiYap() { + muhasebeYapabilme.muhasebeIsiYap(); } + } diff --git a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java b/adapter/src/main/java/com/iluwatar/own/MuhasebeYapabilme.java similarity index 93% rename from adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java rename to adapter/src/main/java/com/iluwatar/own/MuhasebeYapabilme.java index a9ca9ad39717..6618ce9df5aa 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java +++ b/adapter/src/main/java/com/iluwatar/own/MuhasebeYapabilme.java @@ -20,15 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.adapter; +package com.iluwatar.own; /** * The interface expected by the client.
* A rowing boat is rowed to move. * */ -public interface RowingBoat { +public interface MuhasebeYapabilme { - void row(); + void muhasebeIsiYap(); } diff --git a/command/src/main/java/com/iluwatar/command/Size.java b/adapter/src/main/java/com/iluwatar/own/MuhasebeciAdapter.java similarity index 70% rename from command/src/main/java/com/iluwatar/command/Size.java rename to adapter/src/main/java/com/iluwatar/own/MuhasebeciAdapter.java index 25f94a10109b..2c1ce32a36b4 100644 --- a/command/src/main/java/com/iluwatar/command/Size.java +++ b/adapter/src/main/java/com/iluwatar/own/MuhasebeciAdapter.java @@ -1,44 +1,43 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * Enumeration for target size. - * - */ -public enum Size { - - SMALL("small"), NORMAL("normal"); - - private String title; - - Size(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} +/** + * The MIT License + * Copyright (c) 2014-2016 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.own; + +/** + * + * Adapter class. Adapts the interface of the device ({@link VergilendirmeIslemleri}) into {@link MuhasebeYapabilme} + * interface expected by the client ({@link BilgisayarMuhendisi}). + * + */ +public class MuhasebeciAdapter implements MuhasebeYapabilme { + + private VergilendirmeIslemleri vergilendirmeIslemleri; + + public MuhasebeciAdapter() { + vergilendirmeIslemleri = new VergilendirmeIslemleri(); + } + + @Override + public void muhasebeIsiYap() { + vergilendirmeIslemleri.vergiHesapla(); + } +} diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java b/adapter/src/main/java/com/iluwatar/own/VergilendirmeIslemleri.java similarity index 85% rename from adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java rename to adapter/src/main/java/com/iluwatar/own/VergilendirmeIslemleri.java index c46814d18f16..441e06ede61d 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/own/VergilendirmeIslemleri.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.adapter; +package com.iluwatar.own; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,12 +31,12 @@ * Fishing boat moves by sailing. * */ -public class FishingBoat { +public class VergilendirmeIslemleri { - private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class); + private static final Logger LOGGER = LoggerFactory.getLogger(VergilendirmeIslemleri.class); - public void sail() { - LOGGER.info("The fishing boat is sailing"); + public void vergiHesapla() { + LOGGER.info("Vergileri hesaplarim" ); } } diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java deleted file mode 100644 index 9938f055963a..000000000000 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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; - -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -/** - * Test class - * - */ -public class AdapterPatternTest { - - private Map beans; - - private static final String FISHING_BEAN = "fisher"; - - private static final String ROWING_BEAN = "captain"; - - /** - * This method runs before the test execution and sets the bean objects in the beans Map. - */ - @Before - public void setup() { - beans = new HashMap<>(); - - FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter()); - beans.put(FISHING_BEAN, fishingBoatAdapter); - - Captain captain = new Captain(); - captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN)); - beans.put(ROWING_BEAN, captain); - } - - /** - * This test asserts that when we use the row() method on a captain bean(client), it is - * internally calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter} - * ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one - * expected by the client ({@link Captain} ). - */ - @Test - public void testAdapter() { - RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN); - - // when captain moves - captain.row(); - - // the captain internally calls the battleship object to move - RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN); - verify(adapter).row(); - } -} diff --git a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java b/adapter/src/test/java/com/iluwatar/own/AdapterPatternTest.java similarity index 64% rename from bridge/src/test/java/com/iluwatar/bridge/SwordTest.java rename to adapter/src/test/java/com/iluwatar/own/AdapterPatternTest.java index 7ffd0e492c98..61d5da18421f 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java +++ b/adapter/src/test/java/com/iluwatar/own/AdapterPatternTest.java @@ -20,26 +20,45 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.bridge; +package com.iluwatar.own; + +import org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.mock; +import java.util.HashMap; +import java.util.Map; + import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** - * Tests for sword + * Test class + * */ -public class SwordTest extends WeaponTest { +public class AdapterPatternTest { + + + - /** - * Invoke all possible actions on the weapon and check if the actions are executed on the actual - * underlying weapon implementation. - */ @Test - public void testSword() throws Exception { - final Sword sword = spy(new Sword(mock(FlyingEnchantment.class))); - testBasicWeaponActions(sword); + public void testAdapter() { + //given + + MuhasebeciAdapter muhasebeciAdapter = spy(new MuhasebeciAdapter()); // neden spy kullanildi?? + BilgisayarMuhendisi bilgisayarMuhendisi = new BilgisayarMuhendisi(); + + + + // when - bilgisayarMuhendisi muhasebe islerini yapabiliyor + + bilgisayarMuhendisi.setMuhasebeYapabilme(muhasebeciAdapter); + bilgisayarMuhendisi.muhasebeIsiYap(); + + + // then + + // Arka planda muhasebeciAdapterinin muhasebeIsiYap() yordamı 1 kere cagirliyor mu, spy takip eder ? + verify(muhasebeciAdapter).muhasebeIsiYap(); } -} \ No newline at end of file +} diff --git a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/adapter/src/test/java/com/iluwatar/own/AppTest.java similarity index 97% rename from adapter/src/test/java/com/iluwatar/adapter/AppTest.java rename to adapter/src/test/java/com/iluwatar/own/AppTest.java index 213035627615..995c710b617c 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AppTest.java +++ b/adapter/src/test/java/com/iluwatar/own/AppTest.java @@ -20,7 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.adapter; +package com.iluwatar.own; + import org.junit.Test; diff --git a/bridge/README.md b/bridge/README.md index 882640725dae..f8eac8bb3194 100644 --- a/bridge/README.md +++ b/bridge/README.md @@ -20,7 +20,7 @@ Decouple an abstraction from its implementation so that the two can vary indepen Real world example -> Consider you have a weapon with different enchantments and you are supposed to allow mixing different weapons with different enchantments. What would you do? Create multiple copies of each of the weapons for each of the enchantments or would you just create separate enchantment and set it for the weapon as needed? Bridge pattern allows you to do the second. +> Consider you have a vehicle with different enchantments and you are supposed to allow mixing different weapons with different enchantments. What would you do? Create multiple copies of each of the weapons for each of the enchantments or would you just create separate gearBox and set it for the vehicle as needed? Bridge pattern allows you to do the second. In Plain Words @@ -30,155 +30,6 @@ Wikipedia says > The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently" -**Programmatic Example** - -Translating our weapon example from above. Here we have the `Weapon` hierarchy - -``` -public interface Weapon { - void wield(); - void swing(); - void unwield(); - Enchantment getEnchantment(); -} - -public class Sword implements Weapon { - - private final Enchantment enchantment; - - public Sword(Enchantment enchantment) { - this.enchantment = enchantment; - } - - @Override - public void wield() { - LOGGER.info("The sword is wielded."); - enchantment.onActivate(); - } - - @Override - public void swing() { - LOGGER.info("The sword is swinged."); - enchantment.apply(); - } - - @Override - public void unwield() { - LOGGER.info("The sword is unwielded."); - enchantment.onDeactivate(); - } - - @Override - public Enchantment getEnchantment() { - return enchantment; - } -} - -public class Hammer implements Weapon { - - private final Enchantment enchantment; - - public Hammer(Enchantment enchantment) { - this.enchantment = enchantment; - } - - @Override - public void wield() { - LOGGER.info("The hammer is wielded."); - enchantment.onActivate(); - } - - @Override - public void swing() { - LOGGER.info("The hammer is swinged."); - enchantment.apply(); - } - - @Override - public void unwield() { - LOGGER.info("The hammer is unwielded."); - enchantment.onDeactivate(); - } - - @Override - public Enchantment getEnchantment() { - return enchantment; - } -} -``` - -And the separate enchantment hierarchy - -``` -public interface Enchantment { - void onActivate(); - void apply(); - void onDeactivate(); -} - -public class FlyingEnchantment implements Enchantment { - - @Override - public void onActivate() { - LOGGER.info("The item begins to glow faintly."); - } - - @Override - public void apply() { - LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand."); - } - - @Override - public void onDeactivate() { - LOGGER.info("The item's glow fades."); - } -} - -public class SoulEatingEnchantment implements Enchantment { - - @Override - public void onActivate() { - LOGGER.info("The item spreads bloodlust."); - } - - @Override - public void apply() { - LOGGER.info("The item eats the soul of enemies."); - } - - @Override - public void onDeactivate() { - LOGGER.info("Bloodlust slowly disappears."); - } -} -``` - -And both the hierarchies in action - -``` -Sword enchantedSword = new Sword(new SoulEatingEnchantment()); -enchantedSword.wield(); -enchantedSword.swing(); -enchantedSword.unwield(); -// The sword is wielded. -// The item spreads bloodlust. -// The sword is swinged. -// The item eats the soul of enemies. -// The sword is unwielded. -// Bloodlust slowly disappears. - -Hammer hammer = new Hammer(new FlyingEnchantment()); -hammer.wield(); -hammer.swing(); -hammer.unwield(); -// The hammer is wielded. -// The item begins to glow faintly. -// The hammer is swinged. -// The item flies and strikes the enemies finally returning to owner's hand. -// The hammer is unwielded. -// The item's glow fades. -``` - ## Applicability Use the Bridge pattern when diff --git a/bridge/src/main/java/com/iluwatar/bridge/App.java b/bridge/src/main/java/com/iluwatar/bridge/App.java index c986de6565dd..f3ef6ee0e890 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/App.java +++ b/bridge/src/main/java/com/iluwatar/bridge/App.java @@ -30,8 +30,8 @@ * Composition over inheritance. The Bridge pattern can also be thought of as two layers of abstraction. * With Bridge, you can decouple an abstraction from its implementation so that the two can vary independently. *

- * In Bridge pattern both abstraction ({@link Weapon}) and implementation ( - * {@link Enchantment}) have their own class hierarchies. The interface of the implementations + * In Bridge pattern both abstraction ({@link Vehicle}) and implementation ( + * {@link GearBox}) have their own class hierarchies. The interface of the implementations * can be changed without affecting the clients. *

* In this example we have two class hierarchies. One of weapons and another one of enchantments. We can easily @@ -48,16 +48,16 @@ public class App { * @param args command line args */ public static void main(String[] args) { - LOGGER.info("The knight receives an enchanted sword."); - Sword enchantedSword = new Sword(new SoulEatingEnchantment()); - enchantedSword.wield(); - enchantedSword.swing(); - enchantedSword.unwield(); + LOGGER.info("Toyota test"); + Toyota enchantedToyota = new Toyota(new AutomaticGearBox()); + enchantedToyota.startEngine(); + enchantedToyota.drive(); + enchantedToyota.stopEngine(); - LOGGER.info("The valkyrie receives an enchanted hammer."); - Hammer hammer = new Hammer(new FlyingEnchantment()); - hammer.wield(); - hammer.swing(); - hammer.unwield(); + LOGGER.info("Ford test"); + Ford ford = new Ford(new AutomaticGearBox()); + ford.startEngine(); + ford.drive(); + ford.stopEngine(); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/AutomaticGearBox.java similarity index 80% rename from bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java rename to bridge/src/main/java/com/iluwatar/bridge/AutomaticGearBox.java index 8b08d155c083..0c955f83b8e8 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/AutomaticGearBox.java @@ -27,25 +27,25 @@ /** * - * SoulEatingEnchantment + * AutomaticGearBox * */ -public class SoulEatingEnchantment implements Enchantment { +public class AutomaticGearBox implements GearBox { - private static final Logger LOGGER = LoggerFactory.getLogger(SoulEatingEnchantment.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AutomaticGearBox.class); @Override public void onActivate() { - LOGGER.info("The item spreads bloodlust."); + LOGGER.info("Automatic Gear mechanism is activated"); } @Override public void apply() { - LOGGER.info("The item eats the soul of enemies."); + LOGGER.info("The item automatically applied"); } @Override public void onDeactivate() { - LOGGER.info("Bloodlust slowly disappears."); + LOGGER.info("Automatic Gear mechanism is Deactivated."); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java b/bridge/src/main/java/com/iluwatar/bridge/Ford.java similarity index 73% rename from bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java rename to bridge/src/main/java/com/iluwatar/bridge/Ford.java index 8b12c6114e88..0c6d84f743af 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Ford.java @@ -27,25 +27,39 @@ /** * - * FlyingEnchantment + * Ford * */ -public class FlyingEnchantment implements Enchantment { +public class Ford implements Vehicle { - private static final Logger LOGGER = LoggerFactory.getLogger(FlyingEnchantment.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Ford.class); + + private final GearBox gearBox; + + public Ford(GearBox gearBox) { + this.gearBox = gearBox; + } + + @Override + public void startEngine() { + LOGGER.info("Ford is ready to go"); + gearBox.onActivate(); + } @Override - public void onActivate() { - LOGGER.info("The item begins to glow faintly."); + public void drive() { + LOGGER.info("Ford is great ..."); + gearBox.apply(); } @Override - public void apply() { - LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand."); + public void stopEngine() { + LOGGER.info("Ford is unwielded."); + gearBox.onDeactivate(); } @Override - public void onDeactivate() { - LOGGER.info("The item's glow fades."); + public GearBox getGearBox() { + return gearBox; } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java b/bridge/src/main/java/com/iluwatar/bridge/GearBox.java similarity index 96% rename from bridge/src/main/java/com/iluwatar/bridge/Enchantment.java rename to bridge/src/main/java/com/iluwatar/bridge/GearBox.java index dd0c172059cf..12d20b631163 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java +++ b/bridge/src/main/java/com/iluwatar/bridge/GearBox.java @@ -24,10 +24,10 @@ /** * - * Enchantment + * GearBox * */ -public interface Enchantment { +public interface GearBox { void onActivate(); diff --git a/bridge/src/main/java/com/iluwatar/bridge/Sword.java b/bridge/src/main/java/com/iluwatar/bridge/Toyota.java similarity index 68% rename from bridge/src/main/java/com/iluwatar/bridge/Sword.java rename to bridge/src/main/java/com/iluwatar/bridge/Toyota.java index 6f52943a6ead..acf5288cc205 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Sword.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Toyota.java @@ -27,39 +27,39 @@ /** * - * Sword + * Toyota * */ -public class Sword implements Weapon { +public class Toyota implements Vehicle { - private static final Logger LOGGER = LoggerFactory.getLogger(Sword.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Toyota.class); - private final Enchantment enchantment; + private final GearBox gearBox; - public Sword(Enchantment enchantment) { - this.enchantment = enchantment; + public Toyota(GearBox gearBox) { + this.gearBox = gearBox; } @Override - public void wield() { - LOGGER.info("The sword is wielded."); - enchantment.onActivate(); + public void startEngine() { + LOGGER.info("Toyota is ready to go"); + gearBox.onActivate(); } @Override - public void swing() { - LOGGER.info("The sword is swinged."); - enchantment.apply(); + public void drive() { + LOGGER.info("Toyota is great ..."); + gearBox.apply(); } @Override - public void unwield() { - LOGGER.info("The sword is unwielded."); - enchantment.onDeactivate(); + public void stopEngine() { + LOGGER.info("We arrived , stop Toyota"); + gearBox.onDeactivate(); } @Override - public Enchantment getEnchantment() { - return enchantment; + public GearBox getGearBox() { + return gearBox; } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java b/bridge/src/main/java/com/iluwatar/bridge/Vehicle.java similarity index 90% rename from bridge/src/main/java/com/iluwatar/bridge/Weapon.java rename to bridge/src/main/java/com/iluwatar/bridge/Vehicle.java index a2d21b88f5aa..febb02cebd9f 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Weapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Vehicle.java @@ -24,16 +24,16 @@ /** * - * Weapon + * Vehicle * */ -public interface Weapon { +public interface Vehicle { - void wield(); + void startEngine(); - void swing(); + void drive(); - void unwield(); + void stopEngine(); - Enchantment getEnchantment(); + GearBox getGearBox(); } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java b/bridge/src/test/java/com/iluwatar/bridge/VehicleTest.java similarity index 60% rename from bridge/src/main/java/com/iluwatar/bridge/Hammer.java rename to bridge/src/test/java/com/iluwatar/bridge/VehicleTest.java index 51bfda2a1b97..dfa47fba81aa 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Hammer.java +++ b/bridge/src/test/java/com/iluwatar/bridge/VehicleTest.java @@ -22,44 +22,45 @@ */ package com.iluwatar.bridge; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.junit.Test; -/** - * - * Hammer - * - */ -public class Hammer implements Weapon { +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.*; - private static final Logger LOGGER = LoggerFactory.getLogger(Hammer.class); - private final Enchantment enchantment; +public class VehicleTest { - public Hammer(Enchantment enchantment) { - this.enchantment = enchantment; - } - @Override - public void wield() { - LOGGER.info("The hammer is wielded."); - enchantment.onActivate(); - } + @Test + public void testFordActions() { - @Override - public void swing() { - LOGGER.info("The hammer is swinged."); - enchantment.apply(); - } + // given + final Ford vehicle = spy(new Ford(mock(AutomaticGearBox.class))); + assertNotNull(vehicle); + + + // when + GearBox gearBox = vehicle.getGearBox(); + assertNotNull(gearBox); + assertNotNull(vehicle.getGearBox()); + + //then + vehicle.drive(); + verify(gearBox).apply(); + verifyNoMoreInteractions(gearBox); + + vehicle.startEngine(); + verify(gearBox).onActivate(); + verifyNoMoreInteractions(gearBox); + + vehicle.stopEngine(); + verify(gearBox).onDeactivate(); + verifyNoMoreInteractions(gearBox); - @Override - public void unwield() { - LOGGER.info("The hammer is unwielded."); - enchantment.onDeactivate(); } - @Override - public Enchantment getEnchantment() { - return enchantment; + @Test + public void testToyotaActions() { + // TODO } } diff --git a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java deleted file mode 100644 index 0e62374be71e..000000000000 --- a/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.bridge; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.internal.verification.VerificationModeFactory.times; - -/** - * Base class for weapon tests - */ -public abstract class WeaponTest { - - /** - * Invoke the basic actions of the given weapon, and test if the underlying enchantment implementation - * is invoked - * - */ - protected final void testBasicWeaponActions(final Weapon weapon) { - assertNotNull(weapon); - Enchantment enchantment = weapon.getEnchantment(); - assertNotNull(enchantment); - assertNotNull(weapon.getEnchantment()); - - weapon.swing(); - verify(enchantment).apply(); - verifyNoMoreInteractions(enchantment); - - weapon.wield(); - verify(enchantment).onActivate(); - verifyNoMoreInteractions(enchantment); - - weapon.unwield(); - verify(enchantment).onDeactivate(); - verifyNoMoreInteractions(enchantment); - - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/App.java b/builder/src/main/java/com/iluwatar/builder/App.java deleted file mode 100644 index 9fcfdb65ac57..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/App.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -import com.iluwatar.builder.Hero.Builder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * The intention of the Builder pattern is to find a solution to the telescoping constructor - * anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object - * constructor parameter combination leads to an exponential list of constructors. Instead of using - * numerous constructors, the builder pattern uses another object, a builder, that receives each - * initialization parameter step by step and then returns the resulting constructed object at once. - *

- * The Builder pattern has another benefit. It can be used for objects that contain flat data (html - * code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This - * type of data cannot be edited step by step and must be edited at once. The best way to construct - * such an object is to use a builder class. - *

- * In this example we have the Builder pattern variation as described by Joshua Bloch in Effective - * Java 2nd Edition. - *

- * We want to build {@link Hero} objects, but its construction is complex because of the many - * parameters needed. To aid the user we introduce {@link Builder} class. {@link Hero.Builder} - * takes the minimum parameters to build {@link Hero} object in its constructor. After that - * additional configuration for the {@link Hero} object can be done using the fluent - * {@link Builder} interface. When configuration is ready the build method is called to receive - * the final {@link Hero} object. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - - Hero mage = - new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK) - .withWeapon(Weapon.DAGGER).build(); - LOGGER.info(mage.toString()); - - Hero warrior = - new Hero.Builder(Profession.WARRIOR, "Amberjill").withHairColor(HairColor.BLOND) - .withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD) - .build(); - LOGGER.info(warrior.toString()); - - Hero thief = - new Hero.Builder(Profession.THIEF, "Desmond").withHairType(HairType.BALD) - .withWeapon(Weapon.BOW).build(); - LOGGER.info(thief.toString()); - - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/Armor.java b/builder/src/main/java/com/iluwatar/builder/Armor.java deleted file mode 100644 index 0deb9712c2bc..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/Armor.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * Armor enumeration - * - */ -public enum Armor { - - CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); - - private String title; - - Armor(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/HairColor.java b/builder/src/main/java/com/iluwatar/builder/HairColor.java deleted file mode 100644 index a3f03abfc952..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/HairColor.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * HairColor enumeration - * - */ -public enum HairColor { - - WHITE, BLOND, RED, BROWN, BLACK; - - @Override - public String toString() { - return name().toLowerCase(); - } - -} diff --git a/builder/src/main/java/com/iluwatar/builder/HairType.java b/builder/src/main/java/com/iluwatar/builder/HairType.java deleted file mode 100644 index 604a0836d394..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/HairType.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * HairType enumeration - * - */ -public enum HairType { - - BALD("bald"), SHORT("short"), CURLY("curly"), LONG_STRAIGHT("long straight"), LONG_CURLY( - "long curly"); - - private String title; - - HairType(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/Hero.java b/builder/src/main/java/com/iluwatar/builder/Hero.java deleted file mode 100644 index e7f0b3cabbec..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/Hero.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * Hero, the class with many parameters. - * - */ -public final class Hero { - - private final Profession profession; - private final String name; - private final HairType hairType; - private final HairColor hairColor; - private final Armor armor; - private final Weapon weapon; - - private Hero(Builder builder) { - this.profession = builder.profession; - this.name = builder.name; - this.hairColor = builder.hairColor; - this.hairType = builder.hairType; - this.weapon = builder.weapon; - this.armor = builder.armor; - } - - public Profession getProfession() { - return profession; - } - - public String getName() { - return name; - } - - public HairType getHairType() { - return hairType; - } - - public HairColor getHairColor() { - return hairColor; - } - - public Armor getArmor() { - return armor; - } - - public Weapon getWeapon() { - return weapon; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("This is a ") - .append(profession) - .append(" named ") - .append(name); - if (hairColor != null || hairType != null) { - sb.append(" with "); - if (hairColor != null) { - sb.append(hairColor).append(' '); - } - if (hairType != null) { - sb.append(hairType).append(' '); - } - sb.append(hairType != HairType.BALD ? "hair" : "head"); - } - if (armor != null) { - sb.append(" wearing ").append(armor); - } - if (weapon != null) { - sb.append(" and wielding a ").append(weapon); - } - sb.append('.'); - return sb.toString(); - } - - /** - * - * The builder class. - * - */ - public static class Builder { - - private final Profession profession; - private final String name; - private HairType hairType; - private HairColor hairColor; - private Armor armor; - private Weapon weapon; - - /** - * Constructor - */ - public Builder(Profession profession, String name) { - if (profession == null || name == null) { - throw new IllegalArgumentException("profession and name can not be null"); - } - this.profession = profession; - this.name = name; - } - - public Builder withHairType(HairType hairType) { - this.hairType = hairType; - return this; - } - - public Builder withHairColor(HairColor hairColor) { - this.hairColor = hairColor; - return this; - } - - public Builder withArmor(Armor armor) { - this.armor = armor; - return this; - } - - public Builder withWeapon(Weapon weapon) { - this.weapon = weapon; - return this; - } - - public Hero build() { - return new Hero(this); - } - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/Profession.java b/builder/src/main/java/com/iluwatar/builder/Profession.java deleted file mode 100644 index 579eed787baf..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/Profession.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * Profession enumeration - * - */ -public enum Profession { - - WARRIOR, THIEF, MAGE, PRIEST; - - @Override - public String toString() { - return name().toLowerCase(); - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/Weapon.java b/builder/src/main/java/com/iluwatar/builder/Weapon.java deleted file mode 100644 index 86c910a44634..000000000000 --- a/builder/src/main/java/com/iluwatar/builder/Weapon.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -/** - * - * Weapon enumeration - * - */ -public enum Weapon { - - DAGGER, SWORD, AXE, WARHAMMER, BOW; - - @Override - public String toString() { - return name().toLowerCase(); - } -} diff --git a/builder/src/main/java/com/iluwatar/builder/own/NutritionFacts.java b/builder/src/main/java/com/iluwatar/builder/own/NutritionFacts.java new file mode 100644 index 000000000000..bff22ff31ead --- /dev/null +++ b/builder/src/main/java/com/iluwatar/builder/own/NutritionFacts.java @@ -0,0 +1,93 @@ +package com.iluwatar.builder.own; + +public class NutritionFacts { + private final int servingSize; + private final int servings; + private final int calories; + private final int fat; + private final int sodium; + private final int carbohydrate; + + + public static class Builder { + // Required parameters + private final int servingSize; + private final int servings; + + // Optional parameters - initialized to default values + private int calories = 0; + private int fat = 0; + private int carbohydrate = 0; + private int sodium = 0; + + public Builder(int servingSize, int servings) { + this.servingSize = servingSize; + this.servings = servings; + } + + public Builder calories(int val) { + calories = val; + return this; + } + + public Builder fat(int val) { + fat = val; + return this; + } + + public Builder carbohydrate(int val) { + carbohydrate = val; + return this; + } + + public Builder sodium(int val) { + sodium = val; + return this; + } + + public NutritionFacts build() { + if (this.servingSize == 0) { + throw new IllegalArgumentException("servingSize cannot be zero"); + } + return new NutritionFacts(this); + } + } + + public int getServingSize() { + return servingSize; + } + + public int getServings() { + return servings; + } + + public int getCalories() { + return calories; + } + + public int getFat() { + return fat; + } + + public int getSodium() { + return sodium; + } + + public int getCarbohydrate() { + return carbohydrate; + } + + private NutritionFacts(Builder builder) { + servingSize = builder.servingSize; + servings = builder.servings; + calories = builder.calories; + fat = builder.fat; + sodium = builder.sodium; + carbohydrate = builder.carbohydrate; + } + + public static void main(String[] args) { + NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) + .calories(100).sodium(35).carbohydrate(27).build(); + } +} \ No newline at end of file diff --git a/builder/src/main/java/com/iluwatar/builder/own/Serum.java b/builder/src/main/java/com/iluwatar/builder/own/Serum.java new file mode 100644 index 000000000000..c483829ca6e8 --- /dev/null +++ b/builder/src/main/java/com/iluwatar/builder/own/Serum.java @@ -0,0 +1,17 @@ +package com.iluwatar.builder.own; + + +public class Serum { + private final int water = 0; // (mL) required + private final int sodiumIon = 0 ; // required + private final int magnesium = 0; // optional + private final int creatine = 0; // (g) optional + private final int globulin = 0; // (mg) optional + private final int carbohydrate = 0; // (g) optional + + + + public static void main(String[] args) { + // Create A Serum + } +} \ No newline at end of file diff --git a/builder/src/test/java/com/iluwatar/builder/AppTest.java b/builder/src/test/java/com/iluwatar/builder/AppTest.java deleted file mode 100644 index b30c50cda493..000000000000 --- a/builder/src/test/java/com/iluwatar/builder/AppTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.builder; - -import org.junit.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/builder/src/test/java/com/iluwatar/builder/JustTest.java similarity index 60% rename from builder/src/test/java/com/iluwatar/builder/HeroTest.java rename to builder/src/test/java/com/iluwatar/builder/JustTest.java index c111fb853b7f..f2116eda21df 100644 --- a/builder/src/test/java/com/iluwatar/builder/HeroTest.java +++ b/builder/src/test/java/com/iluwatar/builder/JustTest.java @@ -22,32 +22,29 @@ */ package com.iluwatar.builder; +import com.iluwatar.builder.own.NutritionFacts; import org.junit.Test; +import java.util.logging.Logger; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** - * Date: 12/6/15 - 11:01 PM * - * @author Jeroen Meulemeester + * + * @author Altug Altintas */ -public class HeroTest { +public class JustTest { + - /** - * Test if we get the expected exception when trying to create a hero without a profession - */ - @Test(expected = IllegalArgumentException.class) - public void testMissingProfession() throws Exception { - new Hero.Builder(null, "Sir without a job"); - } /** - * Test if we get the expected exception when trying to create a hero without a name + * Test if we get the expected exception when trying to create a NutritionFacts without a servingSize */ @Test(expected = IllegalArgumentException.class) public void testMissingName() throws Exception { - new Hero.Builder(Profession.THIEF, null); + NutritionFacts cocaCola = new NutritionFacts.Builder(0 , 8).build(); } /** @@ -55,23 +52,18 @@ public void testMissingName() throws Exception { */ @Test public void testBuildHero() throws Exception { - final String heroName = "Sir Lancelot"; - final Hero hero = new Hero.Builder(Profession.WARRIOR, heroName) - .withArmor(Armor.CHAIN_MAIL) - .withWeapon(Weapon.SWORD) - .withHairType(HairType.LONG_CURLY) - .withHairColor(HairColor.BLOND) - .build(); - assertNotNull(hero); - assertNotNull(hero.toString()); - assertEquals(Profession.WARRIOR, hero.getProfession()); - assertEquals(heroName, hero.getName()); - assertEquals(Armor.CHAIN_MAIL, hero.getArmor()); - assertEquals(Weapon.SWORD, hero.getWeapon()); - assertEquals(HairType.LONG_CURLY, hero.getHairType()); - assertEquals(HairColor.BLOND, hero.getHairColor()); + NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) + .calories(100).sodium(35).carbohydrate(27).build(); + + assertNotNull(cocaCola); + assertEquals(cocaCola.getServingSize(), 240); + assertEquals(cocaCola.getServings(), 8); + assertEquals(cocaCola.getCalories(), 100); + assertEquals(cocaCola.getSodium(), 35); + assertEquals(cocaCola.getCarbohydrate(), 27); + } diff --git a/chain/README.md b/chain/README.md index 6bca816109b1..b3e6bb97e85c 100644 --- a/chain/README.md +++ b/chain/README.md @@ -29,117 +29,7 @@ Wikipedia says > In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. -**Programmatic Example** -Translating our example with orcs from above. First we have the request class - -``` -public class Request { - - private final RequestType requestType; - private final String requestDescription; - private boolean handled; - - public Request(final RequestType requestType, final String requestDescription) { - this.requestType = Objects.requireNonNull(requestType); - this.requestDescription = Objects.requireNonNull(requestDescription); - } - - public String getRequestDescription() { return requestDescription; } - - public RequestType getRequestType() { return requestType; } - - public void markHandled() { this.handled = true; } - - public boolean isHandled() { return this.handled; } - - @Override - public String toString() { return getRequestDescription(); } -} - -public enum RequestType { - DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX -} -``` - -Then the request handler hierarchy - -``` -public abstract class RequestHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); - private RequestHandler next; - - public RequestHandler(RequestHandler next) { - this.next = next; - } - - public void handleRequest(Request req) { - if (next != null) { - next.handleRequest(req); - } - } - - protected void printHandling(Request req) { - LOGGER.info("{} handling request \"{}\"", this, req); - } - - @Override - public abstract String toString(); -} - -public class OrcCommander extends RequestHandler { - public OrcCommander(RequestHandler handler) { - super(handler); - } - - @Override - public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { - printHandling(req); - req.markHandled(); - } else { - super.handleRequest(req); - } - } - - @Override - public String toString() { - return "Orc commander"; - } -} - -// OrcOfficer and OrcSoldier are defined similarly as OrcCommander - -``` - -Then we have the Orc King who gives the orders and forms the chain - -``` -public class OrcKing { - RequestHandler chain; - - public OrcKing() { - buildChain(); - } - - private void buildChain() { - chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); - } - - public void makeRequest(Request req) { - chain.handleRequest(req); - } -} -``` - -Then it is used as follows - -``` -OrcKing king = new OrcKing(); -king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); // Orc commander handling request "defend castle" -king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); // Orc officer handling request "torture prisoner" -king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); // Orc soldier handling request "collect tax" -``` ## Applicability Use Chain of Responsibility when diff --git a/chain/src/main/java/com/iluwatar/chain/App.java b/chain/src/main/java/com/iluwatar/chain/App.java index 456609e4f366..c2c5e184a58c 100644 --- a/chain/src/main/java/com/iluwatar/chain/App.java +++ b/chain/src/main/java/com/iluwatar/chain/App.java @@ -30,8 +30,8 @@ * chain. A mechanism also exists for adding new processing objects to the end of this chain. *

* In this example we organize the request handlers ({@link RequestHandler}) into a chain where each - * handler has a chance to act on the request on its turn. Here the king ({@link OrcKing}) makes - * requests and the military orcs ({@link OrcCommander}, {@link OrcOfficer}, {@link OrcSoldier}) + * handler has a chance to act on the request on its turn. Here the king ({@link EmailClient}) makes + * requests and the military orcs ({@link GmailHandler}, {@link YahooHandler}, {@link HotmailHandler}) * form the handler chain. * */ @@ -44,10 +44,11 @@ public class App { */ public static void main(String[] args) { - OrcKing king = new OrcKing(); - king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); - king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); - king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); + EmailClient emailClient = new EmailClient(); + emailClient.makeRequest(new Request(RequestType.GMAIL, "Gmail")); + emailClient.makeRequest(new Request(RequestType.YAHOO, "Yahoo")); + emailClient.makeRequest(new Request(RequestType.HOTMAIL, "Hotmail")); + emailClient.makeRequest(new Request(RequestType.YANDEX, "Yandex")); // no handler } } diff --git a/chain/src/main/java/com/iluwatar/chain/OrcKing.java b/chain/src/main/java/com/iluwatar/chain/EmailClient.java similarity index 87% rename from chain/src/main/java/com/iluwatar/chain/OrcKing.java rename to chain/src/main/java/com/iluwatar/chain/EmailClient.java index 35bdbb3c1e46..a64b225e8241 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcKing.java +++ b/chain/src/main/java/com/iluwatar/chain/EmailClient.java @@ -24,19 +24,19 @@ /** * - * OrcKing makes requests that are handled by the chain. + * EmailClient makes requests that are handled by the chain. * */ -public class OrcKing { +public class EmailClient { RequestHandler chain; - public OrcKing() { + public EmailClient() { buildChain(); } private void buildChain() { - chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); + chain = new GmailHandler(new YahooHandler(new HotmailHandler(null))); } public void makeRequest(Request req) { diff --git a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java b/chain/src/main/java/com/iluwatar/chain/GmailHandler.java similarity index 87% rename from chain/src/main/java/com/iluwatar/chain/OrcSoldier.java rename to chain/src/main/java/com/iluwatar/chain/GmailHandler.java index 99e0d5022348..ce7b3ca3c7ab 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java +++ b/chain/src/main/java/com/iluwatar/chain/GmailHandler.java @@ -24,18 +24,18 @@ /** * - * OrcSoldier + * GmailHandler * */ -public class OrcSoldier extends RequestHandler { +public class GmailHandler extends RequestHandler { - public OrcSoldier(RequestHandler handler) { + public GmailHandler(RequestHandler handler) { super(handler); } @Override public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.COLLECT_TAX)) { + if (req.getRequestType().equals(RequestType.GMAIL)) { printHandling(req); req.markHandled(); } else { @@ -45,6 +45,6 @@ public void handleRequest(Request req) { @Override public String toString() { - return "Orc soldier"; + return "Gmail Handler"; } } diff --git a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java b/chain/src/main/java/com/iluwatar/chain/HotmailHandler.java similarity index 87% rename from chain/src/main/java/com/iluwatar/chain/OrcCommander.java rename to chain/src/main/java/com/iluwatar/chain/HotmailHandler.java index 048ba495457f..fee0c8960059 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcCommander.java +++ b/chain/src/main/java/com/iluwatar/chain/HotmailHandler.java @@ -24,18 +24,18 @@ /** * - * OrcCommander + * HotmailHandler * */ -public class OrcCommander extends RequestHandler { +public class HotmailHandler extends RequestHandler { - public OrcCommander(RequestHandler handler) { + public HotmailHandler(RequestHandler handler) { super(handler); } @Override public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) { + if (req.getRequestType().equals(RequestType.HOTMAIL)) { printHandling(req); req.markHandled(); } else { @@ -45,6 +45,6 @@ public void handleRequest(Request req) { @Override public String toString() { - return "Orc commander"; + return "Hotmail Handler"; } } diff --git a/chain/src/main/java/com/iluwatar/chain/Request.java b/chain/src/main/java/com/iluwatar/chain/Request.java index c9ac2505b623..acfbdcf7fcc6 100644 --- a/chain/src/main/java/com/iluwatar/chain/Request.java +++ b/chain/src/main/java/com/iluwatar/chain/Request.java @@ -25,7 +25,7 @@ import java.util.Objects; /** - * Request + * Request = Email object */ public class Request { diff --git a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java index 81e41fb7c120..7f9544baa0d3 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestHandler.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestHandler.java @@ -46,6 +46,8 @@ public RequestHandler(RequestHandler next) { public void handleRequest(Request req) { if (next != null) { next.handleRequest(req); + } else { + LOGGER.info("{} cannot be handled \"{}\"", req); } } diff --git a/chain/src/main/java/com/iluwatar/chain/RequestType.java b/chain/src/main/java/com/iluwatar/chain/RequestType.java index f4d83edc3c94..f2c4648480d6 100644 --- a/chain/src/main/java/com/iluwatar/chain/RequestType.java +++ b/chain/src/main/java/com/iluwatar/chain/RequestType.java @@ -29,6 +29,6 @@ */ public enum RequestType { - DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX + GMAIL, YAHOO, HOTMAIL, YANDEX } diff --git a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java b/chain/src/main/java/com/iluwatar/chain/YahooHandler.java similarity index 87% rename from chain/src/main/java/com/iluwatar/chain/OrcOfficer.java rename to chain/src/main/java/com/iluwatar/chain/YahooHandler.java index 8e90b7ca0bdb..3f6c1f873fb6 100644 --- a/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java +++ b/chain/src/main/java/com/iluwatar/chain/YahooHandler.java @@ -24,18 +24,18 @@ /** * - * OrcOfficer + * YahooHandler * */ -public class OrcOfficer extends RequestHandler { +public class YahooHandler extends RequestHandler { - public OrcOfficer(RequestHandler handler) { + public YahooHandler(RequestHandler handler) { super(handler); } @Override public void handleRequest(Request req) { - if (req.getRequestType().equals(RequestType.TORTURE_PRISONER)) { + if (req.getRequestType().equals(RequestType.YAHOO)) { printHandling(req); req.markHandled(); } else { @@ -45,7 +45,7 @@ public void handleRequest(Request req) { @Override public String toString() { - return "Orc officer"; + return "Yahoo Handler"; } } diff --git a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/chain/src/test/java/com/iluwatar/chain/EmailClientTest.java similarity index 56% rename from proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java rename to chain/src/test/java/com/iluwatar/chain/EmailClientTest.java index 944193a0ab94..5f5c70209ffa 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java +++ b/chain/src/test/java/com/iluwatar/chain/EmailClientTest.java @@ -20,53 +20,54 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.proxy; +package com.iluwatar.chain; -import com.iluwatar.proxy.utils.InMemoryAppender; -import org.junit.After; +import com.iluwatar.chain.helper.InMemoryAppender; import org.junit.Before; import org.junit.Test; -import java.util.Arrays; - import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** - * Tests for {@link IvoryTower} + * Date: 12/6/17 - 13:29 PM + * + * @author Altug Bilgin Altintas */ -public class IvoryTowerTest { +public class EmailClientTest { - private InMemoryAppender appender; + InMemoryAppender appender; @Before public void setUp() { - appender = new InMemoryAppender(IvoryTower.class); - } - - @After - public void tearDown() { - appender.stop(); + appender = new InMemoryAppender(); } @Test - public void testEnter() throws Exception { - final Wizard[] wizards = new Wizard[]{ - new Wizard("Gandalf"), - new Wizard("Dumbledore"), - new Wizard("Oz"), - new Wizard("Merlin") - }; - - IvoryTower tower = new IvoryTower(); - for (Wizard wizard : wizards) { - tower.enter(wizard); - } - - assertTrue(appender.logContains("Gandalf enters the tower.")); - assertTrue(appender.logContains("Dumbledore enters the tower.")); - assertTrue(appender.logContains("Oz enters the tower.")); - assertTrue(appender.logContains("Merlin enters the tower.")); - assertEquals(4, appender.getLogSize()); + public void testMakeRequest() throws Exception { + + + // given + EmailClient emailClient = new EmailClient(); + + // when + emailClient.makeRequest(new Request(RequestType.GMAIL, "Gmail")); + emailClient.makeRequest(new Request(RequestType.YAHOO, "Yahoo")); + emailClient.makeRequest(new Request(RequestType.HOTMAIL, "Hotmail")); + emailClient.makeRequest(new Request(RequestType.YANDEX, "Yandex")); // no handler + + // then + assertTrue(appender.logContains("Gmail Handler handling request \"Gmail\"")); + assertTrue(appender.logContains("Yahoo Handler handling request \"Yahoo\"")); + assertTrue(appender.logContains("Hotmail Handler handling request \"Hotmail\"")); + assertTrue(appender.logContains("Yandex cannot be handled \"{}\"")); + + + + + + } -} + +} \ No newline at end of file diff --git a/chain/src/test/java/com/iluwatar/chain/helper/InMemoryAppender.java b/chain/src/test/java/com/iluwatar/chain/helper/InMemoryAppender.java new file mode 100644 index 000000000000..8869d306ca3f --- /dev/null +++ b/chain/src/test/java/com/iluwatar/chain/helper/InMemoryAppender.java @@ -0,0 +1,32 @@ +package com.iluwatar.chain.helper; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +public class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } +} \ No newline at end of file diff --git a/command/README.md b/command/README.md index 987ec6a34fdc..fcff8f5e61f2 100644 --- a/command/README.md +++ b/command/README.md @@ -19,7 +19,7 @@ Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. -![alt text](./etc/command.png "Command") + ## Applicability Use the Command pattern when you want to diff --git a/command/etc/command.png b/command/etc/command.png deleted file mode 100644 index 81b47d6d0a0c..000000000000 Binary files a/command/etc/command.png and /dev/null differ diff --git a/command/etc/command.ucls b/command/etc/command.ucls deleted file mode 100644 index f0e0857d266c..000000000000 --- a/command/etc/command.ucls +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/App.java b/command/src/main/java/com/iluwatar/command/App.java deleted file mode 100644 index abf2bb4428a3..000000000000 --- a/command/src/main/java/com/iluwatar/command/App.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all - * information needed to perform an action or trigger an event at a later time. This information - * includes the method name, the object that owns the method and values for the method parameters. - *

- * Four terms always associated with the command pattern are command, receiver, invoker and client. - * A command object (spell) knows about the receiver (target) and invokes a method of the receiver. - * Values for parameters of the receiver method are stored in the command. The receiver then does - * the work. An invoker object (wizard) knows how to execute a command, and optionally does - * bookkeeping about the command execution. The invoker does not know anything about a concrete - * command, it knows only about command interface. Both an invoker object and several command - * objects are held by a client object (app). The client decides which commands to execute at which - * points. To execute a command, it passes the command object to the invoker object. - *

- * In other words, in this example the wizard casts spells on the goblin. The wizard keeps track of - * the previous spells cast, so it is easy to undo them. In addition, the wizard keeps track of the - * spells undone, so they can be redone. - * - * - */ -public class App { - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - Wizard wizard = new Wizard(); - Goblin goblin = new Goblin(); - - goblin.printStatus(); - - wizard.castSpell(new ShrinkSpell(), goblin); - goblin.printStatus(); - - wizard.castSpell(new InvisibilitySpell(), goblin); - goblin.printStatus(); - - wizard.undoLastSpell(); - goblin.printStatus(); - - wizard.undoLastSpell(); - goblin.printStatus(); - - wizard.redoLastSpell(); - goblin.printStatus(); - - wizard.redoLastSpell(); - goblin.printStatus(); - } -} diff --git a/command/src/main/java/com/iluwatar/command/Command.java b/command/src/main/java/com/iluwatar/command/Command.java deleted file mode 100644 index 13464a9bce3d..000000000000 --- a/command/src/main/java/com/iluwatar/command/Command.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * Interface for Commands. - * - */ -public abstract class Command { - - public abstract void execute(Target target); - - public abstract void undo(); - - public abstract void redo(); - - @Override - public abstract String toString(); - -} diff --git a/command/src/main/java/com/iluwatar/command/Goblin.java b/command/src/main/java/com/iluwatar/command/Goblin.java deleted file mode 100644 index fac7fdcd643d..000000000000 --- a/command/src/main/java/com/iluwatar/command/Goblin.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * Goblin is the target of the spells - * - */ -public class Goblin extends Target { - - public Goblin() { - setSize(Size.NORMAL); - setVisibility(Visibility.VISIBLE); - } - - @Override - public String toString() { - return "Goblin"; - } - -} diff --git a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java b/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java deleted file mode 100644 index 0622e0a49a0a..000000000000 --- a/command/src/main/java/com/iluwatar/command/InvisibilitySpell.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * InvisibilitySpell is a concrete command - * - */ -public class InvisibilitySpell extends Command { - - private Target target; - - @Override - public void execute(Target target) { - target.setVisibility(Visibility.INVISIBLE); - this.target = target; - } - - @Override - public void undo() { - if (target != null) { - target.setVisibility(Visibility.VISIBLE); - } - } - - @Override - public void redo() { - if (target != null) { - target.setVisibility(Visibility.INVISIBLE); - } - } - - @Override - public String toString() { - return "Invisibility spell"; - } -} diff --git a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java b/command/src/main/java/com/iluwatar/command/ShrinkSpell.java deleted file mode 100644 index eec600d4007b..000000000000 --- a/command/src/main/java/com/iluwatar/command/ShrinkSpell.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * ShrinkSpell is a concrete command - * - */ -public class ShrinkSpell extends Command { - - private Size oldSize; - private Target target; - - @Override - public void execute(Target target) { - oldSize = target.getSize(); - target.setSize(Size.SMALL); - this.target = target; - } - - @Override - public void undo() { - if (oldSize != null && target != null) { - Size temp = target.getSize(); - target.setSize(oldSize); - oldSize = temp; - } - } - - @Override - public void redo() { - undo(); - } - - @Override - public String toString() { - return "Shrink spell"; - } -} diff --git a/command/src/main/java/com/iluwatar/command/Target.java b/command/src/main/java/com/iluwatar/command/Target.java deleted file mode 100644 index 282a4dd469b9..000000000000 --- a/command/src/main/java/com/iluwatar/command/Target.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Base class for spell targets. - * - */ -public abstract class Target { - - private static final Logger LOGGER = LoggerFactory.getLogger(Target.class); - - private Size size; - - private Visibility visibility; - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public Visibility getVisibility() { - return visibility; - } - - public void setVisibility(Visibility visibility) { - this.visibility = visibility; - } - - @Override - public abstract String toString(); - - /** - * Print status - */ - public void printStatus() { - LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility()); - } -} diff --git a/command/src/main/java/com/iluwatar/command/Visibility.java b/command/src/main/java/com/iluwatar/command/Visibility.java deleted file mode 100644 index 8c360d534d2e..000000000000 --- a/command/src/main/java/com/iluwatar/command/Visibility.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -/** - * - * Enumeration for target visibility. - * - */ -public enum Visibility { - - VISIBLE("visible"), INVISIBLE("invisible"); - - private String title; - - Visibility(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } -} diff --git a/command/src/main/java/com/iluwatar/command/Wizard.java b/command/src/main/java/com/iluwatar/command/Wizard.java deleted file mode 100644 index 866ea0e0f0aa..000000000000 --- a/command/src/main/java/com/iluwatar/command/Wizard.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Deque; -import java.util.LinkedList; - -/** - * - * Wizard is the invoker of the commands - * - */ -public class Wizard { - - private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); - - private Deque undoStack = new LinkedList<>(); - private Deque redoStack = new LinkedList<>(); - - public Wizard() { - // comment to ignore sonar issue: LEVEL critical - } - - /** - * Cast spell - */ - public void castSpell(Command command, Target target) { - LOGGER.info("{} casts {} at {}", this, command, target); - command.execute(target); - undoStack.offerLast(command); - } - - /** - * Undo last spell - */ - public void undoLastSpell() { - if (!undoStack.isEmpty()) { - Command previousSpell = undoStack.pollLast(); - redoStack.offerLast(previousSpell); - LOGGER.info("{} undoes {}", this, previousSpell); - previousSpell.undo(); - } - } - - /** - * Redo last spell - */ - public void redoLastSpell() { - if (!redoStack.isEmpty()) { - Command previousSpell = redoStack.pollLast(); - undoStack.offerLast(previousSpell); - LOGGER.info("{} redoes {}", this, previousSpell); - previousSpell.redo(); - } - } - - @Override - public String toString() { - return "Wizard"; - } -} diff --git a/command/src/main/java/com/iluwatar/command/garage/Command.java b/command/src/main/java/com/iluwatar/command/garage/Command.java new file mode 100644 index 000000000000..c6c26fc972dc --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/Command.java @@ -0,0 +1,5 @@ +package com.iluwatar.command.garage; + +public interface Command { + public void execute(); +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garage/GarageDoor.java b/command/src/main/java/com/iluwatar/command/garage/GarageDoor.java new file mode 100644 index 000000000000..65f51275541b --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/GarageDoor.java @@ -0,0 +1,32 @@ +package com.iluwatar.command.garage; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GarageDoor { + + private static final Logger LOGGER = LoggerFactory.getLogger(GarageDoor.class); + + public GarageDoor() { + } + + public void up() { + LOGGER.info("Garage Door is Open"); + } + + public void down() { + LOGGER.info("Garage Door is Closed"); + } + + public void stop() { + LOGGER.info("Garage Door is Stopped"); + } + + public void lightOn() { + LOGGER.info("Garage light is on"); + } + + public void lightOff() { + LOGGER.info("Garage light is off"); + } +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garage/GarageDoorOpenCommand.java b/command/src/main/java/com/iluwatar/command/garage/GarageDoorOpenCommand.java new file mode 100644 index 000000000000..10a5c0376014 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/GarageDoorOpenCommand.java @@ -0,0 +1,13 @@ +package com.iluwatar.command.garage; + +public class GarageDoorOpenCommand implements Command { + GarageDoor garageDoor; + + public GarageDoorOpenCommand(GarageDoor garageDoor) { + this.garageDoor = garageDoor; + } + + public void execute() { + garageDoor.up(); + } +} diff --git a/command/src/main/java/com/iluwatar/command/garage/Light.java b/command/src/main/java/com/iluwatar/command/garage/Light.java new file mode 100644 index 000000000000..65f2c9b40062 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/Light.java @@ -0,0 +1,19 @@ +package com.iluwatar.command.garage; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Light { + + private static final Logger LOGGER = LoggerFactory.getLogger(Light.class); + public Light() { + } + + public void on() { + LOGGER.info("Light is on"); + } + + public void off() { + LOGGER.info("Light is off"); + } +} diff --git a/command/src/main/java/com/iluwatar/command/garage/LightOffCommand.java b/command/src/main/java/com/iluwatar/command/garage/LightOffCommand.java new file mode 100644 index 000000000000..94e433adb566 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/LightOffCommand.java @@ -0,0 +1,13 @@ +package com.iluwatar.command.garage; + +public class LightOffCommand implements Command { + Light light; + + public LightOffCommand(Light light) { + this.light = light; + } + + public void execute() { + light.off(); + } +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garage/LightOnCommand.java b/command/src/main/java/com/iluwatar/command/garage/LightOnCommand.java new file mode 100644 index 000000000000..2744b25ca11c --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/LightOnCommand.java @@ -0,0 +1,13 @@ +package com.iluwatar.command.garage; + +public class LightOnCommand implements Command { + Light light; + + public LightOnCommand(Light light) { + this.light = light; + } + + public void execute() { + light.on(); + } +} diff --git a/command/src/main/java/com/iluwatar/command/garage/RemoteControlTest.java b/command/src/main/java/com/iluwatar/command/garage/RemoteControlTest.java new file mode 100644 index 000000000000..600f77b86339 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/RemoteControlTest.java @@ -0,0 +1,18 @@ +package com.iluwatar.command.garage; + +public class RemoteControlTest { + public static void main(String[] args) { + SimpleRemoteControl remote = new SimpleRemoteControl(); + Light light = new Light(); + GarageDoor garageDoor = new GarageDoor(); + LightOnCommand lightOn = new LightOnCommand(light); + GarageDoorOpenCommand garageOpen = + new GarageDoorOpenCommand(garageDoor); + + remote.setCommand(lightOn); + remote.buttonWasPressed(); + remote.setCommand(garageOpen); + remote.buttonWasPressed(); + } + +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garage/SimpleRemoteControl.java b/command/src/main/java/com/iluwatar/command/garage/SimpleRemoteControl.java new file mode 100644 index 000000000000..69edfb504975 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garage/SimpleRemoteControl.java @@ -0,0 +1,15 @@ +package com.iluwatar.command.garage; + +public class SimpleRemoteControl { + Command slot; + + public SimpleRemoteControl() {} + + public void setCommand(Command command) { + slot = command; + } + + public void buttonWasPressed() { + slot.execute(); + } +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garagenew/Command.java b/command/src/main/java/com/iluwatar/command/garagenew/Command.java new file mode 100644 index 000000000000..c363cba7b5b7 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garagenew/Command.java @@ -0,0 +1,5 @@ +package com.iluwatar.command.garagenew; + +public interface Command { + public void execute(); +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garagenew/GarageDoor.java b/command/src/main/java/com/iluwatar/command/garagenew/GarageDoor.java new file mode 100644 index 000000000000..446cce214052 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garagenew/GarageDoor.java @@ -0,0 +1,27 @@ +package com.iluwatar.command.garagenew; + +public class GarageDoor { + + public GarageDoor() { + } + + public void up() { + System.out.println("Garage Door is Open"); + } + + public void down() { + System.out.println("Garage Door is Closed"); + } + + public void stop() { + System.out.println("Garage Door is Stopped"); + } + + public void lightOn() { + System.out.println("Garage light is on"); + } + + public void lightOff() { + System.out.println("Garage light is off"); + } +} diff --git a/command/src/main/java/com/iluwatar/command/garagenew/Light.java b/command/src/main/java/com/iluwatar/command/garagenew/Light.java new file mode 100644 index 000000000000..3b37eb46603d --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garagenew/Light.java @@ -0,0 +1,15 @@ +package com.iluwatar.command.garagenew; + +public class Light { + + public Light() { + } + + public void on() { + System.out.println("Light is on"); + } + + public void off() { + System.out.println("Light is off"); + } +} \ No newline at end of file diff --git a/command/src/main/java/com/iluwatar/command/garagenew/RemoteControlTest.java b/command/src/main/java/com/iluwatar/command/garagenew/RemoteControlTest.java new file mode 100644 index 000000000000..11d04894bc1f --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garagenew/RemoteControlTest.java @@ -0,0 +1,23 @@ +package com.iluwatar.command.garagenew; + +public class RemoteControlTest { + public static void main(String[] args) { + SimpleRemoteControl remote = new SimpleRemoteControl(); + + Light light = new Light(); + GarageDoor garageDoor = new GarageDoor(); + + remote.setCommand(light::on); + + // TODO what if before Java 8 + + remote.buttonWasPressed(); + remote.setCommand(garageDoor::up); + remote.buttonWasPressed(); + remote.setCommand(garageDoor::lightOn); + remote.buttonWasPressed(); + remote.setCommand(garageDoor::lightOff); + remote.buttonWasPressed(); + } + +} diff --git a/command/src/main/java/com/iluwatar/command/garagenew/SimpleRemoteControl.java b/command/src/main/java/com/iluwatar/command/garagenew/SimpleRemoteControl.java new file mode 100644 index 000000000000..e8076652bd82 --- /dev/null +++ b/command/src/main/java/com/iluwatar/command/garagenew/SimpleRemoteControl.java @@ -0,0 +1,18 @@ +package com.iluwatar.command.garagenew; + +// +// This is the invoker +// +public class SimpleRemoteControl { + Command slot; + + public SimpleRemoteControl() {} + + public void setCommand(Command command) { + slot = command; + } + + public void buttonWasPressed() { + slot.execute(); + } +} \ No newline at end of file diff --git a/command/src/test/java/com/iluwatar/command/AppTest.java b/command/src/test/java/com/iluwatar/command/AppTest.java deleted file mode 100644 index 5b4b742d8e5e..000000000000 --- a/command/src/test/java/com/iluwatar/command/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -import org.junit.Test; - -import java.io.IOException; - -/** - * Tests that Command example runs without errors. - */ -public class AppTest { - @Test - public void test() throws IOException { - String[] args = {}; - App.main(args); - } -} diff --git a/command/src/test/java/com/iluwatar/command/CommandTest.java b/command/src/test/java/com/iluwatar/command/CommandTest.java deleted file mode 100644 index 5c3fa6fe1998..000000000000 --- a/command/src/test/java/com/iluwatar/command/CommandTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.command; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all - * information needed to perform an action or trigger an event at a later time. This information - * includes the method name, the object that owns the method and values for the method parameters. - * - *

Four terms always associated with the command pattern are command, receiver, invoker and - * client. A command object (spell) knows about the receiver (target) and invokes a method of - * the receiver.Values for parameters of the receiver method are stored in the command. The receiver - * then does the work. An invoker object (wizard) knows how to execute a command, and optionally - * does bookkeeping about the command execution. The invoker does not know anything about a - * concrete command, it knows only about command interface. Both an invoker object and several - * command objects are held by a client object (app). The client decides which commands to execute - * at which points. To execute a command, it passes the command object to the invoker object. - */ -public class CommandTest { - - private static final String GOBLIN = "Goblin"; - - /** - * This test verifies that when the wizard casts spells on the goblin. The wizard keeps track of - * the previous spells cast, so it is easy to undo them. In addition, it also verifies that the - * wizard keeps track of the spells undone, so they can be redone. - */ - @Test - public void testCommand() { - - Wizard wizard = new Wizard(); - Goblin goblin = new Goblin(); - - wizard.castSpell(new ShrinkSpell(), goblin); - verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); - - wizard.castSpell(new InvisibilitySpell(), goblin); - verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); - - wizard.undoLastSpell(); - verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); - - wizard.undoLastSpell(); - verifyGoblin(goblin, GOBLIN, Size.NORMAL, Visibility.VISIBLE); - - wizard.redoLastSpell(); - verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); - - wizard.redoLastSpell(); - verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); - } - - /** - * This method asserts that the passed goblin object has the name as expectedName, size as - * expectedSize and visibility as expectedVisibility. - * - * @param goblin a goblin object whose state is to be verified against other parameters - * @param expectedName expectedName of the goblin - * @param expectedSize expected size of the goblin - * @param expectedVisibilty exepcted visibility of the goblin - */ - private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, - Visibility expectedVisibilty) { - assertEquals("Goblin's name must be same as expectedName", expectedName, goblin.toString()); - assertEquals("Goblin's size must be same as expectedSize", expectedSize, goblin.getSize()); - assertEquals("Goblin's visibility must be same as expectedVisibility", expectedVisibilty, - goblin.getVisibility()); - } -} diff --git a/command/src/test/java/com/iluwatar/command/SimpleRemoteControlTest.java b/command/src/test/java/com/iluwatar/command/SimpleRemoteControlTest.java new file mode 100644 index 000000000000..9f6697054e88 --- /dev/null +++ b/command/src/test/java/com/iluwatar/command/SimpleRemoteControlTest.java @@ -0,0 +1,80 @@ +package com.iluwatar.command; + +import com.iluwatar.command.garage.*; +import com.iluwatar.command.helper.InMemoryAppender; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; + +import static org.junit.Assert.assertTrue; + +public class SimpleRemoteControlTest { + + InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + + @Test + public void testCommand() { + + // given + SimpleRemoteControl remote = new SimpleRemoteControl(); + + GarageDoor garageDoor = new GarageDoor(); + Light light = new Light(); + + // when + GarageDoorOpenCommand garageOpen = + new GarageDoorOpenCommand(garageDoor); + LightOnCommand lightOn = new LightOnCommand(light); + + + remote.setCommand(lightOn); + remote.buttonWasPressed(); + remote.setCommand(garageOpen); + remote.buttonWasPressed(); + + // then + assertTrue(appender.logContains("Light is on")); + assertTrue(appender.logContains("Garage Door is Open")); + } + + @Test + public void testCommandPolimorfik() { + // given + SimpleRemoteControl remote = new SimpleRemoteControl(); + ArrayList commandArrayList = new ArrayList(); + + GarageDoor garageDoor = new GarageDoor(); + Light light = new Light(); + + // when + GarageDoorOpenCommand garageOpen = + new GarageDoorOpenCommand(garageDoor); + commandArrayList.add(garageOpen); + + LightOnCommand lightOn = new LightOnCommand(light); + commandArrayList.add(lightOn); + + LightOffCommand lightOffCommand = new LightOffCommand(light); + commandArrayList.add(lightOffCommand); + + + for (Command command: commandArrayList) { + command.execute(); // power of polimorfizm + } + + // then + assertTrue(appender.logContains("Light is on")); + assertTrue(appender.logContains("Garage Door is Open")); + assertTrue(appender.logContains("Light is off")); + + + + } +} diff --git a/command/src/test/java/com/iluwatar/command/helper/InMemoryAppender.java b/command/src/test/java/com/iluwatar/command/helper/InMemoryAppender.java new file mode 100644 index 000000000000..0f82ff408e97 --- /dev/null +++ b/command/src/test/java/com/iluwatar/command/helper/InMemoryAppender.java @@ -0,0 +1,32 @@ +package com.iluwatar.command.helper; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +public class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } +} \ No newline at end of file diff --git a/composite/README.md b/composite/README.md index e4f45ddd0856..130dce32a5fc 100644 --- a/composite/README.md +++ b/composite/README.md @@ -17,9 +17,6 @@ of objects uniformly. ## Explanation -Real world example - -> Every sentence is composed of words which are in turn composed of characters. Each of these objects is printable and they can have something printed before or after them like sentence always ends with full stop and word always has space before it In plain words @@ -29,105 +26,8 @@ Wikipedia says > In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent 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. -**Programmatic Example** - -Taking our sentence example from above. Here we have the base class and different printable types - -``` -public abstract class LetterComposite { - private List children = new ArrayList<>(); - public void add(LetterComposite letter) { - children.add(letter); - } - public int count() { - return children.size(); - } - protected void printThisBefore() {} - protected void printThisAfter() {} - public void print() { - printThisBefore(); - for (LetterComposite letter : children) { - letter.print(); - } - printThisAfter(); - } -} - -public class Letter extends LetterComposite { - private char c; - public Letter(char c) { - this.c = c; - } - @Override - protected void printThisBefore() { - System.out.print(c); - } -} - -public class Word extends LetterComposite { - public Word(List letters) { - for (Letter l : letters) { - this.add(l); - } - } - @Override - protected void printThisBefore() { - System.out.print(" "); - } -} - -public class Sentence extends LetterComposite { - public Sentence(List words) { - for (Word w : words) { - this.add(w); - } - } - @Override - protected void printThisAfter() { - System.out.print("."); - } -} -``` - -Then we have a messenger to carry messages - -``` -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')))); - 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')))); - return new Sentence(words); - } -} -``` - -And then it can be used as - -``` -LetterComposite orcMessage = new Messenger().messageFromOrcs(); -orcMessage.print(); // Where there is a whip there is a way. -LetterComposite elfMessage = new Messenger().messageFromElves(); -elfMessage.print(); // Much wind pours from your mouth. -``` +![alt text](./etc/CompositeDesignPatternGenericHierarchy.gif "Composite Design Pattern GenericHierarchy") +![alt text](./etc/CompositeDesignPatternGeneric.gif "Composite Design PatternGeneric") ## Applicability Use the Composite pattern when diff --git a/composite/etc/CompositeDesignPatternGeneric.gif b/composite/etc/CompositeDesignPatternGeneric.gif new file mode 100644 index 000000000000..04e5aee84500 Binary files /dev/null and b/composite/etc/CompositeDesignPatternGeneric.gif differ diff --git a/composite/etc/CompositeDesignPatternGenericHierarchy.gif b/composite/etc/CompositeDesignPatternGenericHierarchy.gif new file mode 100644 index 000000000000..81bfbb39de62 Binary files /dev/null and b/composite/etc/CompositeDesignPatternGenericHierarchy.gif differ diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java deleted file mode 100644 index 517920ac6906..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Composite pattern is a partitioning design pattern. The Composite pattern describes that a - * group of objects is to be treated in the same way as a single instance of an object. The intent - * 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}). - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - LOGGER.info("Message from the orcs: "); - - LetterComposite orcMessage = new Messenger().messageFromOrcs(); - orcMessage.print(); - - LOGGER.info("\nMessage from the elves: "); - - LetterComposite elfMessage = new Messenger().messageFromElves(); - elfMessage.print(); - } -} diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java deleted file mode 100644 index cd149122d80e..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -/** - * - * Letter - * - */ -public class Letter extends LetterComposite { - - private char c; - - public Letter(char c) { - this.c = c; - } - - @Override - protected void printThisBefore() { - System.out.print(c); - } -} diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java deleted file mode 100644 index f9ff68463628..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * Composite interface. - * - */ -public abstract class LetterComposite { - - private List children = new ArrayList<>(); - - public void add(LetterComposite letter) { - children.add(letter); - } - - public int count() { - return children.size(); - } - - protected void printThisBefore() {} - - protected void printThisAfter() {} - - /** - * Print - */ - public void print() { - printThisBefore(); - for (LetterComposite letter : children) { - letter.print(); - } - printThisAfter(); - } -} diff --git a/composite/src/main/java/com/iluwatar/composite/Messenger.java b/composite/src/main/java/com/iluwatar/composite/Messenger.java deleted file mode 100644 index 998d7e7d0bba..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/Messenger.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * - * 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')))); - - 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')))); - - 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 deleted file mode 100644 index ae844cf59327..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import java.util.List; - -/** - * - * Sentence - * - */ -public class Sentence extends LetterComposite { - - /** - * Constructor - */ - public Sentence(List words) { - for (Word w : words) { - this.add(w); - } - } - - @Override - protected void printThisAfter() { - System.out.print("."); - } -} diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java deleted file mode 100644 index 51e21a2d4f47..000000000000 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import java.util.List; - -/** - * - * Word - * - */ -public class Word extends LetterComposite { - - /** - * Constructor - */ - public Word(List letters) { - for (Letter l : letters) { - this.add(l); - } - } - - @Override - protected void printThisBefore() { - System.out.print(" "); - } -} diff --git a/composite/src/main/java/com/iluwatar/composite/own/Coder.java b/composite/src/main/java/com/iluwatar/composite/own/Coder.java new file mode 100644 index 000000000000..28496b4f6dc8 --- /dev/null +++ b/composite/src/main/java/com/iluwatar/composite/own/Coder.java @@ -0,0 +1,33 @@ +package com.iluwatar.composite.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Coder extends Employee { + + private static final Logger LOGGER = LoggerFactory.getLogger(Coder.class); + + public Coder(String name, double salary) { + this.setName( name ); + this.setSalary(salary ); + + } + + public void add(Employee employee) { + // leaf + } + + public Employee getChild(int i) { + return null; + } + + + public void print() { + LOGGER.info("-------------"); + LOGGER.info("Name ="+getName()); + LOGGER.info("Salary ="+getSalary()); + LOGGER.info("-------------"); + } + + +} diff --git a/composite/src/main/java/com/iluwatar/composite/own/Employee.java b/composite/src/main/java/com/iluwatar/composite/own/Employee.java new file mode 100644 index 000000000000..22a3e9eb2d1b --- /dev/null +++ b/composite/src/main/java/com/iluwatar/composite/own/Employee.java @@ -0,0 +1,53 @@ +package com.iluwatar.composite.own; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public abstract class Employee { + private String name; + private double salary; + + private List employeeList = new ArrayList(); + + private static HashMap salariesMap = new HashMap(); + + public static HashMap getSalariesMap() { + return salariesMap; + } + + public static void setSalariesMap(HashMap salariesMap) { + Employee.salariesMap = salariesMap; + } + + public abstract void add(Employee employee); + + public abstract Employee getChild(int i); + + public abstract void print(); + + + + + public List getEmployeeList() { + return employeeList; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } +} diff --git a/composite/src/main/java/com/iluwatar/composite/own/Manager.java b/composite/src/main/java/com/iluwatar/composite/own/Manager.java new file mode 100644 index 000000000000..316a4134ff5f --- /dev/null +++ b/composite/src/main/java/com/iluwatar/composite/own/Manager.java @@ -0,0 +1,78 @@ +package com.iluwatar.composite.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class Manager extends Employee { + + private static final Logger LOGGER = LoggerFactory.getLogger(Manager.class); + + private List employeeList = new ArrayList(); + + + public Manager(String name, double salary) { + + this.setName(name); + this.setSalary(salary); + + } + + public double getTotalSalary() { + + double total = 0; + + for (String key : getSalariesMap().keySet()) { + total += getSalariesMap().get(key); + } + return total; + + } + + public void reset() { + getSalariesMap().clear(); + } + + + + public void print() { + LOGGER.info("-------------"); + LOGGER.info("Name ="+getName()); + LOGGER.info("Salary ="+getSalary()); + LOGGER.info("-------------"); + + addSalary(getName(), getSalary()); + + Iterator employeeIterator = employeeList.iterator(); + while(employeeIterator.hasNext()){ + Employee employee = employeeIterator.next(); + + addSalary(employee.getName(), employee.getSalary()); + employee.print(); + } + } + + + private void addSalary(String name, Double salary) { + Double salaryLocal = getSalariesMap().get(name); + if (salaryLocal == null) { + getSalariesMap().put(name, salary); + } + } + + + public void add(Employee employee) { + employeeList.add(employee); + } + + public Employee getChild(int i) { + return getEmployeeList().get(i); + } + + + +} diff --git a/composite/src/test/java/com/iluwatar/composite/AppTest.java b/composite/src/test/java/com/iluwatar/composite/AppTest.java deleted file mode 100644 index 0862d5c20a48..000000000000 --- a/composite/src/test/java/com/iluwatar/composite/AppTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import org.junit.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java b/composite/src/test/java/com/iluwatar/composite/EmployeeTest.java similarity index 53% rename from chain/src/test/java/com/iluwatar/chain/OrcKingTest.java rename to composite/src/test/java/com/iluwatar/composite/EmployeeTest.java index 208e6ecb62c0..b74ad7e98e48 100644 --- a/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java +++ b/composite/src/test/java/com/iluwatar/composite/EmployeeTest.java @@ -1,17 +1,17 @@ /** * The MIT License * Copyright (c) 2014-2016 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 @@ -20,40 +20,66 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.chain; +package com.iluwatar.composite; +import com.iluwatar.composite.own.Coder; +import com.iluwatar.composite.own.Manager; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** - * Date: 12/6/15 - 9:29 PM + * Date: 12/11/15 - 8:12 PM * - * @author Jeroen Meulemeester + * @author Altug Bilgin Altintas */ -public class OrcKingTest { - - /** - * All possible requests - */ - private static final Request[] REQUESTS = new Request[]{ - new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), - new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), - new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ..."), - }; - - @Test - public void testMakeRequest() throws Exception { - final OrcKing king = new OrcKing(); - - for (final Request request : REQUESTS) { - king.makeRequest(request); - assertTrue( - "Expected all requests from King to be handled, but [" + request + "] was not!", - request.isHandled() - ); +public class EmployeeTest { + + + + /** + * Test + */ + @Test + public void testMessageFromElves() { + + // given + + Manager generalManager = new Manager("Osman", 50000); + + + Manager manager = new Manager("Nuri", 30000); + Coder coder1 = new Coder("Ayse", 10000); + Coder coder2 = new Coder("Fatma", 9000); + Coder coder3 = new Coder("Zeynep", 9000); + + // when + + manager.add(coder1); + manager.add(coder2); + manager.add(coder3); + + generalManager.add(manager); + + + // then + + generalManager.print(); // recursion + assertEquals(108000, generalManager.getTotalSalary(), 0 ); + + + + generalManager.reset(); + + + manager.print(); + assertEquals(58000, manager.getTotalSalary(), 0 ); + + } - } -} \ No newline at end of file +} diff --git a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/composite/src/test/java/com/iluwatar/composite/MessengerTest.java deleted file mode 100644 index 3746b236ad50..000000000000 --- a/composite/src/test/java/com/iluwatar/composite/MessengerTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.composite; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Date: 12/11/15 - 8:12 PM - * - * @author Jeroen Meulemeester - */ -public class MessengerTest { - - /** - * The buffer used to capture every write to {@link System#out} - */ - private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); - - /** - * Keep the original std-out so it can be restored after the test - */ - private final PrintStream realStdOut = System.out; - - /** - * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test - */ - @Before - public void setUp() { - this.stdOutBuffer = new ByteArrayOutputStream(); - System.setOut(new PrintStream(stdOutBuffer)); - } - - /** - * Removed the mocked std-out {@link PrintStream} again from the {@link System} class - */ - @After - public void tearDown() { - System.setOut(realStdOut); - } - - /** - * Test the message from the orcs - */ - @Test - public void testMessageFromOrcs() { - final Messenger messenger = new Messenger(); - testMessage( - messenger.messageFromOrcs(), - "Where there is a whip there is a way." - ); - } - - /** - * Test the message from the elves - */ - @Test - public void testMessageFromElves() { - final Messenger messenger = new Messenger(); - testMessage( - messenger.messageFromElves(), - "Much wind pours from your mouth." - ); - } - - /** - * Test if the given composed message matches the expected message - * - * @param composedMessage The composed message, received from the messenger - * @param message The expected message - */ - private void testMessage(final LetterComposite composedMessage, final String message) { - // Test is the composed message has the correct number of words - final String[] words = message.split(" "); - assertNotNull(composedMessage); - assertEquals(words.length, composedMessage.count()); - - // Print the message to the mocked stdOut ... - composedMessage.print(); - - // ... and verify if the message matches with the expected one - assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim()); - } - -} diff --git a/decorator/README.md b/decorator/README.md index 4b6bfe61f968..bb6a7a7175dc 100644 --- a/decorator/README.md +++ b/decorator/README.md @@ -13,6 +13,8 @@ tags: ## Also known as Wrapper +## Kahveci + ## Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending @@ -22,7 +24,7 @@ functionality. Real world example -> There is an angry troll living in the nearby hills. Usually it goes bare handed but sometimes it has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable weapon. +> There is an angry troll living in the nearby hills. Usually it goes bare handed but sometimes it has a vehicle. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable vehicle. In plain words @@ -32,82 +34,6 @@ Wikipedia says > In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. -**Programmatic Example** - -Let's take the troll example. First of all we have a simple troll implementing the troll interface - -``` -public interface Troll { - void attack(); - int getAttackPower(); - void fleeBattle(); -} - -public class SimpleTroll implements Troll { - - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTroll.class); - - @Override - public void attack() { - LOGGER.info("The troll tries to grab you!"); - } - - @Override - public int getAttackPower() { - return 10; - } - - @Override - public void fleeBattle() { - LOGGER.info("The troll shrieks in horror and runs away!"); - } -} -``` - -Next we want to add club for the troll. We can do it dynamically by using a decorator - -``` -public class ClubbedTroll implements Troll { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); - - private Troll decorated; - - public ClubbedTroll(Troll decorated) { - this.decorated = decorated; - } - - @Override - public void attack() { - decorated.attack(); - LOGGER.info("The troll swings at you with a club!"); - } - - @Override - public int getAttackPower() { - return decorated.getAttackPower() + 10; - } - - @Override - public void fleeBattle() { - decorated.fleeBattle(); - } -} -``` - -Here's the troll in action - -``` -// simple troll -Troll troll = new SimpleTroll(); -troll.attack(); // The troll tries to grab you! -troll.fleeBattle(); // The troll shrieks in horror and runs away! - -// change the behavior of the simple troll by adding a decorator -troll = new ClubbedTroll(troll); -troll.attack(); // The troll tries to grab you! The troll swings at you with a club! -troll.fleeBattle(); // The troll shrieks in horror and runs away! -``` ## Applicability Use Decorator diff --git a/decorator/kurukahve.pdf b/decorator/kurukahve.pdf new file mode 100644 index 000000000000..30e203297a0b Binary files /dev/null and b/decorator/kurukahve.pdf differ diff --git a/decorator/src/main/java/com/iluwatar/decorator/App.java b/decorator/src/main/java/com/iluwatar/decorator/App.java deleted file mode 100644 index 5b072b9c2dc5..000000000000 --- a/decorator/src/main/java/com/iluwatar/decorator/App.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.decorator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class - * implements the same interface as the target and uses aggregation to "decorate" calls to the - * target. Using the Decorator pattern it is possible to change the behavior of the class during - * runtime. - *

- * In this example we show how the simple {@link SimpleTroll} first attacks and then flees the battle. - * Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the attack again. You - * can see how the behavior changes after the decoration. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - - // simple troll - LOGGER.info("A simple looking troll approaches."); - Troll troll = new SimpleTroll(); - troll.attack(); - troll.fleeBattle(); - LOGGER.info("Simple troll power {}.\n", troll.getAttackPower()); - - // change the behavior of the simple troll by adding a decorator - LOGGER.info("A troll with huge club surprises you."); - troll = new ClubbedTroll(troll); - troll.attack(); - troll.fleeBattle(); - LOGGER.info("Clubbed troll power {}.\n", troll.getAttackPower()); - } -} diff --git a/decorator/src/main/java/com/iluwatar/decorator/JavaIOApp.java b/decorator/src/main/java/com/iluwatar/decorator/JavaIOApp.java new file mode 100644 index 000000000000..f9154ebf5d88 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/JavaIOApp.java @@ -0,0 +1,35 @@ +package com.iluwatar.decorator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; + +public class JavaIOApp { + + private static final Logger LOGGER = LoggerFactory.getLogger(JavaIOApp.class); + + public static void main(String args[]) throws IOException { + + + BufferedReader bufferedReader = null; + + try { + ClassLoader cl = ClassLoader.getSystemClassLoader(); + bufferedReader = new BufferedReader(new InputStreamReader(cl.getResourceAsStream("file.txt"))); + + + String line = null; + while((line = bufferedReader.readLine()) != null) { + LOGGER.info(line); + } + + } catch (IOException ex) { + ex.getStackTrace(); + } finally { + bufferedReader.close(); + } + + + } +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/Troll.java b/decorator/src/main/java/com/iluwatar/decorator/Troll.java deleted file mode 100644 index ffc7e5b527d9..000000000000 --- a/decorator/src/main/java/com/iluwatar/decorator/Troll.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.decorator; - -/** - * - * Interface for trolls - * - */ -public interface Troll { - - void attack(); - - int getAttackPower(); - - void fleeBattle(); - -} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Beverage.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Beverage.java new file mode 100755 index 000000000000..dae43df03693 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Beverage.java @@ -0,0 +1,11 @@ +package com.iluwatar.decorator.starbuckz; + +public abstract class Beverage { + String description = "Unknown Beverage"; + + public String getDescription() { + return description; + } + + public abstract double cost(); +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/CondimentDecorator.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/CondimentDecorator.java new file mode 100755 index 000000000000..17146642cc76 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/CondimentDecorator.java @@ -0,0 +1,5 @@ +package com.iluwatar.decorator.starbuckz; + +public abstract class CondimentDecorator extends Beverage { + public abstract String getDescription(); +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/DarkRoast.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/DarkRoast.java new file mode 100755 index 000000000000..a54afc7378ab --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/DarkRoast.java @@ -0,0 +1,12 @@ +package com.iluwatar.decorator.starbuckz; + +public class DarkRoast extends Beverage { + public DarkRoast() { + description = "Dark Roast Coffee"; + } + + public double cost() { + return .99; + } +} + diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Decaf.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Decaf.java new file mode 100755 index 000000000000..f8bf1e8e83a9 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Decaf.java @@ -0,0 +1,12 @@ +package com.iluwatar.decorator.starbuckz; + +public class Decaf extends Beverage { + public Decaf() { + description = "Decaf Coffee"; + } + + public double cost() { + return 1.05; + } +} + diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Espresso.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Espresso.java new file mode 100755 index 000000000000..a1b7280651f6 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Espresso.java @@ -0,0 +1,13 @@ +package com.iluwatar.decorator.starbuckz; + +public class Espresso extends Beverage { + + public Espresso() { + description = "Espresso"; + } + + public double cost() { + return 1.99; + } +} + diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/HouseBlend.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/HouseBlend.java new file mode 100755 index 000000000000..7fe3308bf2aa --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/HouseBlend.java @@ -0,0 +1,12 @@ +package com.iluwatar.decorator.starbuckz; + +public class HouseBlend extends Beverage { + public HouseBlend() { + description = "House Blend Coffee"; + } + + public double cost() { + return .89; + } +} + diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Milk.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Milk.java new file mode 100755 index 000000000000..b96f509d00d2 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Milk.java @@ -0,0 +1,17 @@ +package com.iluwatar.decorator.starbuckz; + +public class Milk extends CondimentDecorator { + Beverage beverage; + + public Milk(Beverage beverage) { + this.beverage = beverage; + } + + public String getDescription() { + return beverage.getDescription() + ", Milk"; + } + + public double cost() { + return .10 + beverage.cost(); + } +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Mocha.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Mocha.java new file mode 100755 index 000000000000..311a20534f38 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Mocha.java @@ -0,0 +1,17 @@ +package com.iluwatar.decorator.starbuckz; + +public class Mocha extends CondimentDecorator { + Beverage beverage; + + public Mocha(Beverage beverage) { + this.beverage = beverage; + } + + public String getDescription() { + return beverage.getDescription() + ", Mocha"; + } + + public double cost() { + return .20 + beverage.cost(); + } +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Soy.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Soy.java new file mode 100755 index 000000000000..ac7461a2754d --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Soy.java @@ -0,0 +1,17 @@ +package com.iluwatar.decorator.starbuckz; + +public class Soy extends CondimentDecorator { + Beverage beverage; + + public Soy(Beverage beverage) { + this.beverage = beverage; + } + + public String getDescription() { + return beverage.getDescription() + ", Soy"; + } + + public double cost() { + return .15 + beverage.cost(); + } +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/StarbuzzCoffee.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/StarbuzzCoffee.java new file mode 100755 index 000000000000..fe5b3c644350 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/StarbuzzCoffee.java @@ -0,0 +1,24 @@ +package com.iluwatar.decorator.starbuckz; + +public class StarbuzzCoffee { + + public static void main(String args[]) { + Beverage beverage = new Espresso(); + System.out.println(beverage.getDescription() + + " $" + beverage.cost()); + + Beverage beverage2 = new DarkRoast(); + beverage2 = new Mocha(beverage2); + beverage2 = new Mocha(beverage2); + beverage2 = new Whip(beverage2); + System.out.println(beverage2.getDescription() + + " $" + beverage2.cost()); + + Beverage beverage3 = new HouseBlend(); + beverage3 = new Soy(beverage3); + beverage3 = new Mocha(beverage3); + beverage3 = new Whip(beverage3); + System.out.println(beverage3.getDescription() + + " $" + beverage3.cost()); + } +} diff --git a/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Whip.java b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Whip.java new file mode 100755 index 000000000000..cb3a446d77b6 --- /dev/null +++ b/decorator/src/main/java/com/iluwatar/decorator/starbuckz/Whip.java @@ -0,0 +1,17 @@ +package com.iluwatar.decorator.starbuckz; + +public class Whip extends CondimentDecorator { + Beverage beverage; + + public Whip(Beverage beverage) { + this.beverage = beverage; + } + + public String getDescription() { + return beverage.getDescription() + ", Whip"; + } + + public double cost() { + return .10 + beverage.cost(); + } +} diff --git a/decorator/src/main/resources/file.txt b/decorator/src/main/resources/file.txt new file mode 100644 index 000000000000..9b15e5338957 --- /dev/null +++ b/decorator/src/main/resources/file.txt @@ -0,0 +1,2 @@ +Merhaba +Naber ? diff --git a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/decorator/src/test/java/com/iluwatar/decorator/AppTest.java deleted file mode 100644 index 466fa1552416..000000000000 --- a/decorator/src/test/java/com/iluwatar/decorator/AppTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.decorator; - -import org.junit.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/CoffeeTest.java similarity index 65% rename from decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java rename to decorator/src/test/java/com/iluwatar/decorator/CoffeeTest.java index fb86615c68ff..002975fad2e9 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/CoffeeTest.java @@ -22,6 +22,9 @@ */ package com.iluwatar.decorator; +import com.iluwatar.decorator.starbuckz.Beverage; +import com.iluwatar.decorator.starbuckz.Espresso; +import com.iluwatar.decorator.starbuckz.Mocha; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -29,26 +32,26 @@ import static org.mockito.internal.verification.VerificationModeFactory.times; /** - * Tests for {@link ClubbedTroll} + * Tests for {@link } */ -public class ClubbedTrollTest { +public class CoffeeTest { @Test - public void testClubbedTroll() throws Exception { - // Create a normal troll first, but make sure we can spy on it later on. - final Troll simpleTroll = spy(new SimpleTroll()); - - // Now we want to decorate the troll to make it stronger ... - final Troll clubbed = new ClubbedTroll(simpleTroll); - assertEquals(20, clubbed.getAttackPower()); - verify(simpleTroll, times(1)).getAttackPower(); - - // Check if the clubbed troll actions are delegated to the decorated troll - clubbed.attack(); - verify(simpleTroll, times(1)).attack(); - - clubbed.fleeBattle(); - verify(simpleTroll, times(1)).fleeBattle(); - verifyNoMoreInteractions(simpleTroll); + public void testCoffee() throws Exception { + + // given - Create a Espresso + final Beverage beverage = spy(new Espresso()); + + + + // when - Now we want to decorate Espresso + final Beverage clubbed = new Mocha(beverage); + assertEquals(2.19, clubbed.cost(),0); + assertEquals("Espresso, Mocha" , clubbed.getDescription()); + + // then + verify(beverage, times(1)).getDescription(); + + } } diff --git a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java deleted file mode 100644 index 5c6b2bbe798e..000000000000 --- a/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.decorator; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@link SimpleTroll} - */ -public class SimpleTrollTest { - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(SimpleTroll.class); - } - - @After - public void tearDown() { - appender.stop(); - } - - @Test - public void testTrollActions() throws Exception { - final SimpleTroll troll = new SimpleTroll(); - assertEquals(10, troll.getAttackPower()); - - troll.attack(); - assertEquals("The troll tries to grab you!", appender.getLastMessage()); - - troll.fleeBattle(); - assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage()); - - assertEquals(2, appender.getLogSize()); - } - - private class InMemoryAppender extends AppenderBase { - - private List log = new LinkedList<>(); - - public InMemoryAppender(Class clazz) { - ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); - start(); - } - - @Override - protected void append(ILoggingEvent eventObject) { - log.add(eventObject); - } - - public String getLastMessage() { - return log.get(log.size() - 1).getMessage(); - } - - public int getLogSize() { - return log.size(); - } - } -} diff --git a/facade/README.md b/facade/README.md index 7caa89d94684..b50667524e01 100644 --- a/facade/README.md +++ b/facade/README.md @@ -14,6 +14,9 @@ tags: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. +## Diagram +Show Diagram + ## Explanation Real world example diff --git a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java index 6457307cf2b8..9fce55c95ee4 100644 --- a/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java +++ b/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -99,6 +99,8 @@ public void testFullWorkDay() { assertTrue(appender.logContains("Dwarf cart operator goes home.")); assertTrue(appender.logContains("Dwarven tunnel digger goes home.")); + //TODO add watch tv + // ... and go to sleep. We need well rested workers the next day :) assertTrue(appender.logContains("Dwarf gold digger goes to sleep.")); assertTrue(appender.logContains("Dwarf cart operator goes to sleep.")); @@ -106,6 +108,8 @@ public void testFullWorkDay() { // Every worker should be sleeping now, no other actions allowed assertEquals(15, appender.getLogSize()); + + } private class InMemoryAppender extends AppenderBase { diff --git a/factory-method/README.md b/factory-method/README.md index 7432a3cb56fd..337ea1d8f853 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -21,7 +21,7 @@ instantiation to subclasses. ## Explanation Real world example -> Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons. Depending on the customer at hand the right type of blacksmith is summoned. +> Blacksmith manufactures cars. Toyota cars requires Toyota factory and Ford cars requires Ford factory. Depending on the customer at hand the right type of blacksmith is summoned. In plain words @@ -31,36 +31,7 @@ Wikipedia says > In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by 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. - **Programmatic Example** - -Taking our blacksmith example above. First of all we have a blacksmith interface and some implementations for it - -``` -public interface Blacksmith { - Weapon manufactureWeapon(WeaponType weaponType); -} - -public class ElfBlacksmith implements Blacksmith { - public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); - } -} - -public class OrcBlacksmith implements Blacksmith { - public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); - } -} -``` - -Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured - -``` -Blacksmith blacksmith = new ElfBlacksmith(); -blacksmith.manufactureWeapon(WeaponType.SPEAR); -blacksmith.manufactureWeapon(WeaponType.AXE); -// Elvish weapons are created -``` + ## Applicability Use the Factory Method pattern when 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 3fb1056821ea..bd2c7d84a8f8 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 @@ -34,8 +34,8 @@ * derived classes—rather than by calling a constructor. *

* 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 + * creating objects ({@link Blacksmith#manufactureVehicle}). The concrete subclasses ( + * {@link FordBlacksmith}, {@link ToyotaBlacksmith}) then override the method to produce objects of * their liking. * */ @@ -47,10 +47,9 @@ public class App { /** * Creates an instance of App which will use blacksmith to manufacture - * the weapons for war. + * the Vehicle . * App is unaware which concrete implementation of {@link Blacksmith} it is using. - * The decision of which blacksmith implementation to use may depend on configuration, or - * the type of rival in war. + * The decision of which blacksmith implementation to use may depend on configuration * @param blacksmith a non-null implementation of blacksmith */ public App(Blacksmith blacksmith) { @@ -63,20 +62,21 @@ public App(Blacksmith blacksmith) { * @param args command line args */ public static void main(String[] args) { - // Lets go to war with Orc weapons - App app = new App(new OrcBlacksmith()); - app.manufactureWeapons(); - - // Lets go to war with Elf weapons - app = new App(new ElfBlacksmith()); - app.manufactureWeapons(); + + // Lets produce Ford Vehicles + App app = new App(new FordBlacksmith()); + app.manufactureVehicles(); + + // Lets produce Toyota Vehicles + app = new App(new ToyotaBlacksmith()); + app.manufactureVehicles(); } - private void manufactureWeapons() { - Weapon weapon; - weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - LOGGER.info(weapon.toString()); - weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - LOGGER.info(weapon.toString()); + private void manufactureVehicles() { + Vehicle vehicle; + vehicle = blacksmith.manufactureVehicle(VehicleType.HYBRID); + LOGGER.info(vehicle.toString()); + vehicle = blacksmith.manufactureVehicle(VehicleType.SEDAN); + LOGGER.info(vehicle.toString()); } } 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 e856d467eb6e..f886c171a295 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 @@ -29,6 +29,6 @@ */ public interface Blacksmith { - Weapon manufactureWeapon(WeaponType weaponType); + Vehicle manufactureVehicle(VehicleType vehicleType); } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/FordBlacksmith.java similarity index 88% rename from factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java rename to factory-method/src/main/java/com/iluwatar/factory/method/FordBlacksmith.java index 66938bb1773b..ad4021463611 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/FordBlacksmith.java @@ -27,10 +27,9 @@ * Concrete subclass for creating new objects. * */ -public class ElfBlacksmith implements Blacksmith { +public class FordBlacksmith implements Blacksmith { - public Weapon manufactureWeapon(WeaponType weaponType) { - return new ElfWeapon(weaponType); + public Vehicle manufactureVehicle(VehicleType vehicleType) { + return new FordVehicle(vehicleType); } - } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/FordVehicle.java similarity index 81% rename from factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java rename to factory-method/src/main/java/com/iluwatar/factory/method/FordVehicle.java index 95771e248b9e..c0e8a84ab95f 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/FordVehicle.java @@ -23,23 +23,23 @@ package com.iluwatar.factory.method; /** - * ElfWeapon. + * FordVehicle. */ -public class ElfWeapon implements Weapon { +public class FordVehicle implements Vehicle { - private WeaponType weaponType; + private VehicleType vehicleType; - public ElfWeapon(WeaponType weaponType) { - this.weaponType = weaponType; + public FordVehicle(VehicleType vehicleType) { + this.vehicleType = vehicleType; } @Override public String toString() { - return "Elven " + weaponType; + return "Ford " + vehicleType; } @Override - public WeaponType getWeaponType() { - return weaponType; + public VehicleType getVehicleType() { + return vehicleType; } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java b/factory-method/src/main/java/com/iluwatar/factory/method/ToyotaBlacksmith.java similarity index 88% rename from factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java rename to factory-method/src/main/java/com/iluwatar/factory/method/ToyotaBlacksmith.java index e2921a4b52cf..56e3f169d6fc 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcBlacksmith.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ToyotaBlacksmith.java @@ -27,9 +27,10 @@ * Concrete subclass for creating new objects. * */ -public class OrcBlacksmith implements Blacksmith { +public class ToyotaBlacksmith implements Blacksmith { - public Weapon manufactureWeapon(WeaponType weaponType) { - return new OrcWeapon(weaponType); + public Vehicle manufactureVehicle(VehicleType vehicleType) { + return new ToyotaVehicle(vehicleType); } + } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/ToyotaVehicle.java similarity index 81% rename from factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java rename to factory-method/src/main/java/com/iluwatar/factory/method/ToyotaVehicle.java index 59ae0e7dc639..2caae69bada9 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/OrcWeapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/ToyotaVehicle.java @@ -23,23 +23,23 @@ package com.iluwatar.factory.method; /** - * OrcWeapon. + * ToyotaVehicle. */ -public class OrcWeapon implements Weapon { +public class ToyotaVehicle implements Vehicle { - private WeaponType weaponType; + private VehicleType vehicleType; - public OrcWeapon(WeaponType weaponType) { - this.weaponType = weaponType; + public ToyotaVehicle(VehicleType vehicleType) { + this.vehicleType = vehicleType; } @Override public String toString() { - return "Orcish " + weaponType; + return "Toyota " + vehicleType; } @Override - public WeaponType getWeaponType() { - return weaponType; + public VehicleType getVehicleType() { + return vehicleType; } } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java b/factory-method/src/main/java/com/iluwatar/factory/method/Vehicle.java similarity index 93% rename from factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java rename to factory-method/src/main/java/com/iluwatar/factory/method/Vehicle.java index c642622c3313..460a1e775168 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/Vehicle.java @@ -23,10 +23,10 @@ package com.iluwatar.factory.method; /** - * Weapon interface. + * Vehicle interface. */ -public interface Weapon { +public interface Vehicle { - WeaponType getWeaponType(); + VehicleType getVehicleType(); } diff --git a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java b/factory-method/src/main/java/com/iluwatar/factory/method/VehicleType.java similarity index 89% rename from factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java rename to factory-method/src/main/java/com/iluwatar/factory/method/VehicleType.java index 9f5ce18764bb..176779bba0f2 100644 --- a/factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java +++ b/factory-method/src/main/java/com/iluwatar/factory/method/VehicleType.java @@ -24,16 +24,16 @@ /** * - * WeaponType enumeration + * VehicleType enumeration * */ -public enum WeaponType { +public enum VehicleType { - SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED(""); + TRUCK("truck"), HYBRID("hybrid"), SEDAN("sedan"), UNDEFINED(""); private String title; - WeaponType(String title) { + VehicleType(String title) { this.title = title; } diff --git a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java index 69736855ca8e..c2ef78caac88 100644 --- a/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java +++ b/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -35,67 +35,87 @@ * derived classes—rather than by calling a constructor. * *

Factory produces the object of its liking. - * The weapon {@link Weapon} manufactured by the + * The weapon {@link Vehicle} manufactured by the * blacksmith depends on the kind of factory implementation it is referring to. *

*/ public class FactoryMethodTest { /** - * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link FordBlacksmith} to produce a HYBRID asserting that the Vehicle is an instance + * of {@link FordVehicle}. */ @Test - public void testOrcBlacksmithWithSpear() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); + public void testFordBlacksmithWithHybrid() { + // given + Blacksmith blacksmith = new FordBlacksmith(); + + // when + Vehicle vehicle = blacksmith.manufactureVehicle(VehicleType.HYBRID); + + // then + verifyVehicle(vehicle, VehicleType.HYBRID, FordVehicle.class); } /** - * Testing {@link OrcBlacksmith} to produce a AXE asserting that the Weapon is an instance - * of {@link OrcWeapon}. + * Testing {@link FordBlacksmith} to produce a SEDAN asserting that the Vehicle is an instance + * of {@link FordVehicle}. */ @Test - public void testOrcBlacksmithWithAxe() { - Blacksmith blacksmith = new OrcBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); - verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); + public void testFordBlacksmithWithSedan() { + // given + Blacksmith blacksmith = new FordBlacksmith(); + + // when + Vehicle vehicle = blacksmith.manufactureVehicle(VehicleType.SEDAN); + + // then + verifyVehicle(vehicle, VehicleType.SEDAN, FordVehicle.class); } /** - * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an - * instance of {@link ElfWeapon}. + * Testing {@link ToyotaBlacksmith} to produce a TRUCK asserting that the Vehicle is an + * instance of {@link ToyotaVehicle}. */ @Test - public void testElfBlacksmithWithShortSword() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); - verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); + public void testToyotaBlacksmithWithTruck() { + // given + Blacksmith blacksmith = new ToyotaBlacksmith(); + + // when + Vehicle vehicle = blacksmith.manufactureVehicle(VehicleType.TRUCK); + + // then + verifyVehicle(vehicle, VehicleType.TRUCK, ToyotaVehicle.class); } /** - * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance - * of {@link ElfWeapon}. + * Testing {@link ToyotaBlacksmith} to produce a HYBRID asserting that the Vehicle is an instance + * of {@link ToyotaVehicle}. */ @Test - public void testElfBlacksmithWithSpear() { - Blacksmith blacksmith = new ElfBlacksmith(); - Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); - verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); + public void testToyotaBlacksmithWithHybrid() { + // given + Blacksmith blacksmith = new ToyotaBlacksmith(); + + // when + Vehicle vehicle = blacksmith.manufactureVehicle(VehicleType.HYBRID); + + // then + verifyVehicle(vehicle, VehicleType.HYBRID, ToyotaVehicle.class); } /** - * This method asserts that the weapon object that is passed is an instance of the clazz and the - * weapon is of type expectedWeaponType. + * This method asserts that the vehicle object that is passed is an instance of the clazz and the + * vehicle is of type expectedVehicleType. * - * @param weapon weapon object which is to be verified - * @param expectedWeaponType expected WeaponType of the weapon - * @param clazz expected class of the weapon + * @param vehicle vehicle object which is to be verified + * @param expectedVehicleType expected VehicleType of the vehicle + * @param clazz expected class of the vehicle */ - private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { - assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon)); - assertEquals("Weapon must be of weaponType: " + expectedWeaponType, expectedWeaponType, - weapon.getWeaponType()); + private void verifyVehicle(Vehicle vehicle, VehicleType expectedVehicleType, Class clazz) { + assertTrue("Vehicle must be an object of: " + clazz.getName(), clazz.isInstance(vehicle)); + assertEquals("Vehicle must be of weaponType: " + expectedVehicleType, expectedVehicleType, + vehicle.getVehicleType()); } } diff --git a/iterator/README.md b/iterator/README.md index 723e7f03cd20..b35b1513f14c 100644 --- a/iterator/README.md +++ b/iterator/README.md @@ -17,7 +17,7 @@ Cursor Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. -![alt text](./etc/iterator_1.png "Iterator") +![alt text](./etc/iterator_pattern.png "Iterator") ## Applicability Use the Iterator pattern diff --git a/iterator/etc/iterator.png b/iterator/etc/iterator.png deleted file mode 100644 index f70340951409..000000000000 Binary files a/iterator/etc/iterator.png and /dev/null differ diff --git a/iterator/etc/iterator.ucls b/iterator/etc/iterator.ucls deleted file mode 100644 index 440f9a28bb00..000000000000 --- a/iterator/etc/iterator.ucls +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/iterator/etc/iterator_1.png b/iterator/etc/iterator_1.png deleted file mode 100644 index d8313bc5881f..000000000000 Binary files a/iterator/etc/iterator_1.png and /dev/null differ diff --git a/iterator/etc/iterator_pattern.png b/iterator/etc/iterator_pattern.png new file mode 100644 index 000000000000..af296676710c Binary files /dev/null and b/iterator/etc/iterator_pattern.png differ diff --git a/iterator/src/main/java/com/iluwatar/iterator/App.java b/iterator/src/main/java/com/iluwatar/iterator/App.java deleted file mode 100644 index d283347cba23..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/App.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * The Iterator pattern is a design pattern in which an iterator is used to traverse a container and - * access the container's elements. The Iterator pattern decouples algorithms from containers. - *

- * In this example the Iterator ({@link ItemIterator}) adds abstraction layer on top of a collection - * ({@link TreasureChest}). This way the collection can change its internal implementation without - * affecting its clients. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * Program entry point - * - * @param args command line args - */ - public static void main(String[] args) { - TreasureChest chest = new TreasureChest(); - - ItemIterator ringIterator = chest.iterator(ItemType.RING); - while (ringIterator.hasNext()) { - LOGGER.info(ringIterator.next().toString()); - } - - LOGGER.info("----------"); - - ItemIterator potionIterator = chest.iterator(ItemType.POTION); - while (potionIterator.hasNext()) { - LOGGER.info(potionIterator.next().toString()); - } - - LOGGER.info("----------"); - - ItemIterator weaponIterator = chest.iterator(ItemType.WEAPON); - while (weaponIterator.hasNext()) { - LOGGER.info(weaponIterator.next().toString()); - } - - LOGGER.info("----------"); - - ItemIterator it = chest.iterator(ItemType.ANY); - while (it.hasNext()) { - LOGGER.info(it.next().toString()); - } - } -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/Item.java b/iterator/src/main/java/com/iluwatar/iterator/Item.java deleted file mode 100644 index 47bc11354d43..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/Item.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -/** - * - * Item - * - */ -public class Item { - - private ItemType type; - private String name; - - public Item(ItemType type, String name) { - this.setType(type); - this.name = name; - } - - @Override - public String toString() { - return name; - } - - public ItemType getType() { - return type; - } - - public final void setType(ItemType type) { - this.type = type; - } -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java deleted file mode 100644 index 0eab2f075334..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/ItemIterator.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -/** - * - * ItemIterator interface. - * - */ -public interface ItemIterator { - - boolean hasNext(); - - Item next(); -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java b/iterator/src/main/java/com/iluwatar/iterator/ItemType.java deleted file mode 100644 index 4cf36926efee..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/ItemType.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -/** - * - * ItemType enumeration - * - */ -public enum ItemType { - - ANY, WEAPON, RING, POTION - -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java deleted file mode 100644 index 4b9959269fa3..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * TreasureChest, the collection class. - * - */ -public class TreasureChest { - - private List items; - - /** - * 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")); - } - - ItemIterator iterator(ItemType itemType) { - return new TreasureChestItemIterator(this, itemType); - } - - /** - * Get all items - */ - public List getItems() { - List list = new ArrayList<>(); - list.addAll(items); - return list; - } - -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java b/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java deleted file mode 100644 index 9d841259ff26..000000000000 --- a/iterator/src/main/java/com/iluwatar/iterator/TreasureChestItemIterator.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -import java.util.List; - -/** - * - * TreasureChestItemIterator - * - */ -public class TreasureChestItemIterator implements ItemIterator { - - private TreasureChest chest; - private int idx; - private ItemType type; - - /** - * Constructor - */ - public TreasureChestItemIterator(TreasureChest chest, ItemType type) { - this.chest = chest; - this.type = type; - this.idx = -1; - } - - @Override - public boolean hasNext() { - return findNextIdx() != -1; - } - - @Override - public Item next() { - idx = findNextIdx(); - if (idx != -1) { - return chest.getItems().get(idx); - } - return null; - } - - private int findNextIdx() { - - List items = chest.getItems(); - boolean found = false; - int tempIdx = idx; - while (!found) { - tempIdx++; - if (tempIdx >= items.size()) { - tempIdx = -1; - break; - } - if (type.equals(ItemType.ANY) || items.get(tempIdx).getType().equals(type)) { - break; - } - } - return tempIdx; - } -} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/ChannelIterator.java b/iterator/src/main/java/com/iluwatar/iterator/own/ChannelIterator.java new file mode 100644 index 000000000000..460f2abfb9c7 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/ChannelIterator.java @@ -0,0 +1,8 @@ +package com.iluwatar.iterator.own; + +//Iterator interface +public interface ChannelIterator{ + public boolean hasNext(); + public void next(); + public String currentItem(); +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteChannelIterator.java b/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteChannelIterator.java new file mode 100644 index 000000000000..96e75d47a6fd --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteChannelIterator.java @@ -0,0 +1,32 @@ +package com.iluwatar.iterator.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +//Concrete Iterator //Iterator interface +public class ConcreteChannelIterator implements ChannelIterator{ + + private static final Logger LOGGER = LoggerFactory.getLogger(ConcreteChannelIterator.class); + private List channels; + private int currentPos = 0; + public ConcreteChannelIterator(List channels){ + this.channels = channels; + } + + public boolean hasNext(){ + if(currentPos < channels.size()){ + return true; + } + return false; + } + public void next(){ + currentPos++; + } + public String currentItem(){ + String currentItem = channels.get(currentPos); + LOGGER.info(currentItem); + return currentItem; + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteTV.java b/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteTV.java new file mode 100644 index 000000000000..8e16252725bc --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/ConcreteTV.java @@ -0,0 +1,19 @@ +package com.iluwatar.iterator.own; + +import java.util.List; + +//Concrete Aggregator +public class ConcreteTV implements TV { + + ChannelIterator iterator; + + + public ConcreteTV(List channels){ + iterator = new ConcreteChannelIterator(channels); + } + public ChannelIterator getIterator(){ + return iterator; + } + + +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/Pure.java b/iterator/src/main/java/com/iluwatar/iterator/own/Pure.java new file mode 100644 index 000000000000..84e512f45189 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/Pure.java @@ -0,0 +1,25 @@ +package com.iluwatar.iterator.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class Pure { + + private static final Logger LOGGER = LoggerFactory.getLogger(Pure.class); + public static void main(String args[]) { + List list = new ArrayList(); + list.add("Ankara"); + list.add("Mersin"); + list.add("Afyon"); + + Iterator it = list.iterator(); + while(it.hasNext()){ + String s = it.next(); + LOGGER.info(" > " + s ); + } + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/RunTv.java b/iterator/src/main/java/com/iluwatar/iterator/own/RunTv.java new file mode 100644 index 000000000000..148f0f39c408 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/RunTv.java @@ -0,0 +1,24 @@ +package com.iluwatar.iterator.own; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class RunTv { + + public static void main(String args[]) { + List channells = new ArrayList(); + channells.add("A kanali"); + channells.add("B kanali"); + channells.add("C kanali"); + + ConcreteTV concreteTV = new ConcreteTV(channells); + + ChannelIterator it = concreteTV.getIterator(); + while(it.hasNext()){ + + System.out.println(" > " + it.currentItem() ); + it.next(); + } + } +} diff --git a/iterator/src/main/java/com/iluwatar/iterator/own/TV.java b/iterator/src/main/java/com/iluwatar/iterator/own/TV.java new file mode 100644 index 000000000000..c2f1226f88e1 --- /dev/null +++ b/iterator/src/main/java/com/iluwatar/iterator/own/TV.java @@ -0,0 +1,6 @@ +package com.iluwatar.iterator.own; + +//Aggregate interface +public interface TV { + public ChannelIterator getIterator();//other TV methods +} \ No newline at end of file diff --git a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/iterator/src/test/java/com/iluwatar/iterator/AppTest.java deleted file mode 100644 index 75cad3ced7b7..000000000000 --- a/iterator/src/test/java/com/iluwatar/iterator/AppTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -import org.junit.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java deleted file mode 100644 index 196e0821626e..000000000000 --- a/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.iterator; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -/** - * Date: 12/14/15 - 2:58 PM - * - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class TreasureChestTest { - - /** - * Create a list of all expected items in the chest. - * - * @return The set of all expected items in the chest - */ - @Parameterized.Parameters - public static List data() { - 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; - } - - /** - * One of the expected items in the chest - */ - private final Item expectedItem; - - /** - * Create a new test instance, test if the given expected item can be retrieved from the chest - * - * @param expectedItem One of the items that should be in the chest - */ - public TreasureChestTest(final Item expectedItem) { - this.expectedItem = expectedItem; - } - - /** - * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} - */ - @Test - public void testIterator() { - final TreasureChest chest = new TreasureChest(); - final ItemIterator iterator = chest.iterator(expectedItem.getType()); - assertNotNull(iterator); - - while (iterator.hasNext()) { - final Item item = iterator.next(); - assertNotNull(item); - assertEquals(this.expectedItem.getType(), item.getType()); - - final String name = item.toString(); - assertNotNull(name); - if (this.expectedItem.toString().equals(name)) { - return; - } - } - - fail("Expected to find item [" + this.expectedItem + "] using iterator, but we didn't."); - - } - - /** - * Test if the expected item can be retrieved from the chest using the {@link - * TreasureChest#getItems()} method - */ - @Test - public void testGetItems() throws Exception { - final TreasureChest chest = new TreasureChest(); - final List items = chest.getItems(); - assertNotNull(items); - - for (final Item item : items) { - assertNotNull(item); - assertNotNull(item.getType()); - assertNotNull(item.toString()); - - final boolean sameType = this.expectedItem.getType() == item.getType(); - final boolean sameName = this.expectedItem.toString().equals(item.toString()); - if (sameType && sameName) { - return; - } - } - - fail("Expected to find item [" + this.expectedItem + "] in the item list, but we didn't."); - - } - -} \ No newline at end of file diff --git a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/iterator/src/test/java/com/iluwatar/iterator/TvTest.java similarity index 53% rename from observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java rename to iterator/src/test/java/com/iluwatar/iterator/TvTest.java index a61a91afe060..cdd996ecf5bb 100644 --- a/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java +++ b/iterator/src/test/java/com/iluwatar/iterator/TvTest.java @@ -20,43 +20,66 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.observer.generic; - -import com.iluwatar.observer.WeatherType; +package com.iluwatar.iterator; +import com.iluwatar.iterator.own.ChannelIterator; +import com.iluwatar.iterator.own.ConcreteTV; +import helper.InMemoryAppender; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import static org.junit.Assert.*; + /** - * Date: 12/27/15 - 12:07 PM + * Date: 12/14/17 - 2:58 PM * - * @author Jeroen Meulemeester + * @author Altug Altintas */ -@RunWith(Parameterized.class) -public class OrcsTest extends ObserverTest { - - @Parameterized.Parameters - public static Collection data() { - 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; - } +public class TvTest { + + InMemoryAppender appender; + + @Before + public void setup() { + appender = new InMemoryAppender(); + + } /** - * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer + * Test if the expected item can be retrieved from the channels. */ - public OrcsTest(final WeatherType weather, final String response) { - super(weather, response, GOrcs::new); + @Test + public void testIterator() { + + // Given + List channells = new ArrayList(); + channells.add("A kanali"); + channells.add("B kanali"); + channells.add("C kanali"); + + ConcreteTV concreteTV = new ConcreteTV(channells); + assertNotNull(concreteTV); + + // When + ChannelIterator concreteTVIterator = concreteTV.getIterator(); + while(concreteTVIterator.hasNext()){ + assertNotNull(concreteTVIterator.currentItem()); + concreteTVIterator.next(); + } + + + // Then + assertTrue(appender.logContains("A kanali")); + assertTrue(appender.logContains("B kanali")); + assertTrue(appender.logContains("C kanali")); + } -} + + +} \ No newline at end of file diff --git a/iterator/src/test/java/helper/InMemoryAppender.java b/iterator/src/test/java/helper/InMemoryAppender.java new file mode 100644 index 000000000000..f6f3748c62c8 --- /dev/null +++ b/iterator/src/test/java/helper/InMemoryAppender.java @@ -0,0 +1,32 @@ +package helper; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +public class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } +} \ No newline at end of file diff --git a/observer/etc/observer.ucls b/observer/etc/observer.ucls index 87a3dd216d4e..87b46e798c2b 100644 --- a/observer/etc/observer.ucls +++ b/observer/etc/observer.ucls @@ -5,7 +5,7 @@ file="/observer/src/main/java/com/iluwatar/observer/Hobbits.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -14,7 +14,7 @@ file="/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -23,7 +23,7 @@ file="/observer/src/main/java/com/iluwatar/observer/Orcs.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -32,7 +32,7 @@ file="/observer/src/main/java/com/iluwatar/observer/Weather.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -41,7 +41,7 @@ file="/observer/src/main/java/com/iluwatar/observer/WeatherType.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -71,7 +71,7 @@ + sort-features="false" accessors="true" mobility="true"> diff --git a/observer/src/main/java/com/iluwatar/observer/App.java b/observer/src/main/java/com/iluwatar/observer/App.java index 84bad3382c3b..a3ef07dc7c7a 100644 --- a/observer/src/main/java/com/iluwatar/observer/App.java +++ b/observer/src/main/java/com/iluwatar/observer/App.java @@ -22,9 +22,7 @@ */ package com.iluwatar.observer; -import com.iluwatar.observer.generic.GHobbits; -import com.iluwatar.observer.generic.GOrcs; -import com.iluwatar.observer.generic.GWeather; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,15 +59,6 @@ public static void main(String[] args) { weather.timePasses(); weather.timePasses(); - // Generic observer inspired by Java Generics and Collection by Naftalin & Wadler - LOGGER.info("--Running generic version--"); - GWeather gWeather = new GWeather(); - gWeather.addObserver(new GOrcs()); - gWeather.addObserver(new GHobbits()); - gWeather.timePasses(); - gWeather.timePasses(); - gWeather.timePasses(); - gWeather.timePasses(); } } diff --git a/observer/src/main/java/com/iluwatar/observer/Weather.java b/observer/src/main/java/com/iluwatar/observer/Weather.java index 3c9cb209b666..dafbbaf1a448 100644 --- a/observer/src/main/java/com/iluwatar/observer/Weather.java +++ b/observer/src/main/java/com/iluwatar/observer/Weather.java @@ -56,10 +56,11 @@ public void removeObserver(WeatherObserver obs) { /** * Makes time pass for weather + * Gives next weather condition systematically */ public void timePasses() { WeatherType[] enumValues = WeatherType.values(); - currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; + currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; // gives next weather LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(); } diff --git a/observer/src/main/java/com/iluwatar/observer/WeatherType.java b/observer/src/main/java/com/iluwatar/observer/WeatherType.java index 0e66a000dda1..1c2e00e2a3d4 100644 --- a/observer/src/main/java/com/iluwatar/observer/WeatherType.java +++ b/observer/src/main/java/com/iluwatar/observer/WeatherType.java @@ -29,7 +29,7 @@ */ public enum WeatherType { - SUNNY, RAINY, WINDY, COLD; + SUNNY, RAINY, WINDY, COLD; @Override public String toString() { diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java b/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java deleted file mode 100644 index 5e0afbc81627..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/GHobbits.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.WeatherType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * GHobbits - * - */ -public class GHobbits implements Race { - - private static final Logger LOGGER = LoggerFactory.getLogger(GHobbits.class); - - @Override - public void update(GWeather weather, WeatherType weatherType) { - switch (weatherType) { - case COLD: - LOGGER.info("The hobbits are shivering in the cold weather."); - break; - case RAINY: - LOGGER.info("The hobbits look for cover from the rain."); - break; - case SUNNY: - LOGGER.info("The happy hobbits bade in the warm sun."); - break; - case WINDY: - LOGGER.info("The hobbits hold their hats tightly in the windy weather."); - break; - default: - break; - } - } -} diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java b/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java deleted file mode 100644 index 734cf0e69f69..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/GOrcs.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.WeatherType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * GOrcs - * - */ -public class GOrcs implements Race { - - private static final Logger LOGGER = LoggerFactory.getLogger(GOrcs.class); - - @Override - public void update(GWeather weather, WeatherType weatherType) { - switch (weatherType) { - case COLD: - LOGGER.info("The orcs are freezing cold."); - break; - case RAINY: - LOGGER.info("The orcs are dripping wet."); - break; - case SUNNY: - LOGGER.info("The sun hurts the orcs' eyes."); - break; - case WINDY: - LOGGER.info("The orc smell almost vanishes in the wind."); - break; - default: - break; - } - } -} diff --git a/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java b/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java deleted file mode 100644 index 19e72d140028..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/GWeather.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.WeatherType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * GWeather - * - */ -public class GWeather extends Observable { - - private static final Logger LOGGER = LoggerFactory.getLogger(GWeather.class); - - private WeatherType currentWeather; - - public GWeather() { - currentWeather = WeatherType.SUNNY; - } - - /** - * Makes time pass for weather - */ - public void timePasses() { - WeatherType[] enumValues = WeatherType.values(); - currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; - LOGGER.info("The weather changed to {}.", currentWeather); - notifyObservers(currentWeather); - } -} diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java b/observer/src/main/java/com/iluwatar/observer/generic/Observable.java deleted file mode 100644 index ff204437ded7..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observable.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * Generic observer inspired by Java Generics and Collection by Naftalin & Wadler - * - * @param Subject - * @param Observer - * @param Argument type - */ -public abstract class Observable, O extends Observer, A> { - - protected List observers; - - public Observable() { - this.observers = new CopyOnWriteArrayList<>(); - } - - public void addObserver(O observer) { - this.observers.add(observer); - } - - public void removeObserver(O observer) { - this.observers.remove(observer); - } - - /** - * Notify observers - */ - @SuppressWarnings("unchecked") - public void notifyObservers(A argument) { - for (O observer : observers) { - observer.update((S) this, argument); - } - } -} diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java b/observer/src/main/java/com/iluwatar/observer/generic/Observer.java deleted file mode 100644 index f8c30853b8b6..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/Observer.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -/** - * Observer - * @param Observable - * @param Observer - * @param Action - */ -public interface Observer, O extends Observer, A> { - - void update(S subject, A argument); -} diff --git a/observer/src/main/java/com/iluwatar/observer/generic/Race.java b/observer/src/main/java/com/iluwatar/observer/generic/Race.java deleted file mode 100644 index 16f2e8e6728a..000000000000 --- a/observer/src/main/java/com/iluwatar/observer/generic/Race.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.WeatherType; - -/** - * - * Race - * - */ -public interface Race extends Observer { -} diff --git a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java deleted file mode 100644 index 31a4fd6670f9..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Date: 12/27/15 - 12:07 PM - * - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class HobbitsTest extends WeatherObserverTest { - - @Parameterized.Parameters - public static Collection data() { - 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; - } - - /** - * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer - */ - public HobbitsTest(final WeatherType weather, final String response) { - super(weather, response, Hobbits::new); - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/observer/src/test/java/com/iluwatar/observer/OrcsTest.java deleted file mode 100644 index b1f0b82d7548..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/OrcsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Date: 12/27/15 - 12:07 PM - * - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class OrcsTest extends WeatherObserverTest { - - @Parameterized.Parameters - public static Collection data() { - 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; - } - - /** - * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer - */ - public OrcsTest(final WeatherType weather, final String response) { - super(weather, response, Orcs::new); - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java deleted file mode 100644 index 70a7922c56d8..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer; - -import static org.junit.Assert.assertEquals; - -import com.iluwatar.observer.utils.InMemoryAppender; -import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Date: 12/27/15 - 11:44 AM - * Weather Observer Tests - * @param Type of WeatherObserver - * @author Jeroen Meulemeester - */ -public abstract class WeatherObserverTest { - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(); - } - - @After - public void tearDown() { - appender.stop(); - } - - /** - * The observer instance factory - */ - private final Supplier factory; - - /** - * The weather type currently tested - */ - private final WeatherType weather; - - /** - * The expected response from the observer - */ - private final String response; - - /** - * Create a new test instance using the given parameters - * - * @param weather The weather currently being tested - * @param response The expected response from the observer - * @param factory The factory, used to create an instance of the tested observer - */ - WeatherObserverTest(final WeatherType weather, final String response, final Supplier factory) { - this.weather = weather; - this.response = response; - this.factory = factory; - } - - /** - * Verify if the weather has the expected influence on the observer - */ - @Test - public void testObserver() { - final O observer = this.factory.get(); - assertEquals(0, appender.getLogSize()); - - observer.update(this.weather); - assertEquals(response, appender.getLastMessage()); - assertEquals(1, appender.getLogSize()); - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java index 88bf1c4c3523..e3885d182adc 100644 --- a/observer/src/test/java/com/iluwatar/observer/WeatherTest.java +++ b/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -29,11 +29,7 @@ import org.mockito.InOrder; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.*; /** * Date: 12/27/15 - 11:08 AM @@ -60,41 +56,32 @@ public void tearDown() { */ @Test public void testAddRemoveObserver() { + + // Given final WeatherObserver observer = mock(WeatherObserver.class); final Weather weather = new Weather(); weather.addObserver(observer); - verifyZeroInteractions(observer); + + // When weather.timePasses(); + + // Then assertEquals("The weather changed to rainy.", appender.getLastMessage()); verify(observer).update(WeatherType.RAINY); + + // When weather.removeObserver(observer); weather.timePasses(); - assertEquals("The weather changed to windy.", appender.getLastMessage()); - verifyNoMoreInteractions(observer); + // Then + assertEquals("The weather changed to windy.", appender.getLastMessage()); + verifyNoMoreInteractions(observer); // make sure no call on Observer object even weather has changed. assertEquals(2, appender.getLogSize()); } - /** - * Verify if the weather passes in the order of the {@link WeatherType}s - */ - @Test - public void testTimePasses() { - final WeatherObserver observer = mock(WeatherObserver.class); - final Weather weather = new Weather(); - weather.addObserver(observer); - - final InOrder inOrder = inOrder(observer); - final WeatherType[] weatherTypes = WeatherType.values(); - for (int i = 1; i < 20; i++) { - weather.timePasses(); - inOrder.verify(observer).update(weatherTypes[i % weatherTypes.length]); - } +} - verifyNoMoreInteractions(observer); - } -} diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java deleted file mode 100644 index a54f15689e57..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.Hobbits; -import com.iluwatar.observer.WeatherObserverTest; -import com.iluwatar.observer.WeatherType; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Date: 12/27/15 - 12:07 PM - * - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class GHobbitsTest extends ObserverTest { - - @Parameterized.Parameters - public static Collection data() { - 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; - } - - /** - * Create a new test with the given weather and expected response - * - * @param weather The weather that should be unleashed on the observer - * @param response The expected response from the observer - */ - public GHobbitsTest(final WeatherType weather, final String response) { - super(weather, response, GHobbits::new); - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java b/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java deleted file mode 100644 index ab15ca884b5a..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import com.iluwatar.observer.WeatherObserver; -import com.iluwatar.observer.WeatherType; -import com.iluwatar.observer.utils.InMemoryAppender; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InOrder; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - -/** - * Date: 12/27/15 - 11:08 AM - * - * @author Jeroen Meulemeester - */ -public class GWeatherTest { - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(GWeather.class); - } - - @After - public void tearDown() { - appender.stop(); - } - - /** - * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the - * observer again and verify that there are no more notifications. - */ - @Test - public void testAddRemoveObserver() { - final Race observer = mock(Race.class); - - final GWeather weather = new GWeather(); - weather.addObserver(observer); - verifyZeroInteractions(observer); - - weather.timePasses(); - assertEquals("The weather changed to rainy.", appender.getLastMessage()); - verify(observer).update(weather, WeatherType.RAINY); - - weather.removeObserver(observer); - weather.timePasses(); - assertEquals("The weather changed to windy.", appender.getLastMessage()); - - verifyNoMoreInteractions(observer); - assertEquals(2, appender.getLogSize()); - } - - /** - * Verify if the weather passes in the order of the {@link WeatherType}s - */ - @Test - public void testTimePasses() { - final Race observer = mock(Race.class); - final GWeather weather = new GWeather(); - weather.addObserver(observer); - - final InOrder inOrder = inOrder(observer); - final WeatherType[] weatherTypes = WeatherType.values(); - for (int i = 1; i < 20; i++) { - weather.timePasses(); - inOrder.verify(observer).update(weather, weatherTypes[i % weatherTypes.length]); - } - - verifyNoMoreInteractions(observer); - } - -} diff --git a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java b/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java deleted file mode 100644 index 930f7533f130..000000000000 --- a/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.observer.generic; - -import static org.junit.Assert.assertEquals; - -import com.iluwatar.observer.WeatherType; -import com.iluwatar.observer.utils.InMemoryAppender; -import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Date: 12/27/15 - 11:44 AM - * Test for Observers - * @param Type of Observer - * @author Jeroen Meulemeester - */ -public abstract class ObserverTest { - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(); - } - - @After - public void tearDown() { - appender.stop(); - } - - /** - * The observer instance factory - */ - private final Supplier factory; - - /** - * The weather type currently tested - */ - private final WeatherType weather; - - /** - * The expected response from the observer - */ - private final String response; - - /** - * Create a new test instance using the given parameters - * - * @param weather The weather currently being tested - * @param response The expected response from the observer - * @param factory The factory, used to create an instance of the tested observer - */ - ObserverTest(final WeatherType weather, final String response, final Supplier factory) { - this.weather = weather; - this.response = response; - this.factory = factory; - } - - /** - * Verify if the weather has the expected influence on the observer - */ - @Test - public void testObserver() { - final O observer = this.factory.get(); - assertEquals(0, appender.getLogSize()); - - observer.update(null, this.weather); - assertEquals(this.response, appender.getLastMessage()); - assertEquals(1, appender.getLogSize()); - } - -} diff --git a/prototype/src/main/java/com/iluwatar/prototype/App.java b/prototype/src/main/java/com/iluwatar/prototype/App.java index dfebdab17605..0e2d140fa724 100644 --- a/prototype/src/main/java/com/iluwatar/prototype/App.java +++ b/prototype/src/main/java/com/iluwatar/prototype/App.java @@ -48,20 +48,24 @@ public class App { */ public static void main(String[] args) { HeroFactory factory; + Mage mage; Warlord warlord; Beast beast; factory = new HeroFactoryImpl(new ElfMage(), new ElfWarlord(), new ElfBeast()); + mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); + LOGGER.info(mage.toString()); LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); factory = new HeroFactoryImpl(new OrcMage(), new OrcWarlord(), new OrcBeast()); mage = factory.createMage(); + warlord = factory.createWarlord(); beast = factory.createBeast(); LOGGER.info(mage.toString()); diff --git a/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java b/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java index bee05bc5e263..62acf940741b 100644 --- a/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java +++ b/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java @@ -25,10 +25,7 @@ import org.junit.Test; import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; /** * Date: 12/28/15 - 8:34 PM @@ -39,6 +36,8 @@ public class HeroFactoryImplTest { @Test public void testFactory() throws Exception { + + // given final Mage mage = mock(Mage.class); final Warlord warlord = mock(Warlord.class); final Beast beast = mock(Beast.class); @@ -47,11 +46,22 @@ public void testFactory() throws Exception { when(warlord.clone()).thenThrow(CloneNotSupportedException.class); when(beast.clone()).thenThrow(CloneNotSupportedException.class); + /* + TODO : prove and understand mock mechanism + 1 - beast.clone(); // will throw exception + 2 - comment line 47 + 3 - verify(beast, times(2)).clone(); + */ + + // when + final HeroFactoryImpl factory = new HeroFactoryImpl(mage, warlord, beast); assertNull(factory.createMage()); assertNull(factory.createWarlord()); assertNull(factory.createBeast()); + // then + verify(mage).clone(); verify(warlord).clone(); verify(beast).clone(); diff --git a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java deleted file mode 100644 index 839f27bc7147..000000000000 --- a/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.prototype; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; - -import java.util.Arrays; -import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -/** - * Date: 12/28/15 - 8:45 PM - * @param

Prototype - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class PrototypeTest

{ - - @Parameterized.Parameters - public static Collection data() { - return Arrays.asList( - new Object[]{new OrcBeast(), "Orcish wolf"}, - new Object[]{new OrcMage(), "Orcish mage"}, - new Object[]{new OrcWarlord(), "Orcish warlord"}, - new Object[]{new ElfBeast(), "Elven eagle"}, - new Object[]{new ElfMage(), "Elven mage"}, - new Object[]{new ElfWarlord(), "Elven warlord"} - ); - } - - /** - * The tested prototype instance - */ - private final P testedPrototype; - - /** - * The expected {@link Prototype#toString()} value - */ - private final String expectedToString; - - /** - * Create a new test instance, using the given test object and expected value - * - * @param testedPrototype The tested prototype instance - * @param expectedToString The expected {@link Prototype#toString()} value - */ - public PrototypeTest(final P testedPrototype, final String expectedToString) { - this.expectedToString = expectedToString; - this.testedPrototype = testedPrototype; - } - - @Test - public void testPrototype() throws Exception { - assertEquals(this.expectedToString, this.testedPrototype.toString()); - - final Object clone = this.testedPrototype.clone(); - assertNotNull(clone); - assertNotSame(clone, this.testedPrototype); - assertSame(this.testedPrototype.getClass(), clone.getClass()); - } - -} diff --git a/proxy/README.md b/proxy/README.md index 80593c75e1c1..3b8213e5b81a 100644 --- a/proxy/README.md +++ b/proxy/README.md @@ -11,7 +11,7 @@ tags: --- ## Also known as -Surrogate +Surrogate (Vekil) ## Intent Provide a surrogate or placeholder for another object to control @@ -20,7 +20,7 @@ access to it. ## Explanation Real world example -> Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it. + > Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it. In plain words @@ -32,26 +32,26 @@ Wikipedia says **Programmatic Example** -Taking our wizard tower example from above. Firstly we have the wizard tower interface and the ivory tower class +Taking our user tower example from above. Firstly we have the user tower interface and the ivory tower class ``` public interface WizardTower { - void enter(Wizard wizard); + void enter(Wizard user); } public class IvoryTower implements WizardTower { private static final Logger LOGGER = LoggerFactory.getLogger(IvoryTower.class); - public void enter(Wizard wizard) { - LOGGER.info("{} enters the tower.", wizard); + public void enter(Wizard user) { + LOGGER.info("{} enters the tower.", user); } } ``` -Then a simple wizard class +Then a simple user class ``` public class Wizard { @@ -69,7 +69,7 @@ public class Wizard { } ``` -Then we have the proxy to add access control to wizard tower +Then we have the proxy to add access control to user tower ``` public class WizardTowerProxy implements WizardTower { @@ -87,12 +87,12 @@ public class WizardTowerProxy implements WizardTower { } @Override - public void enter(Wizard wizard) { + public void enter(Wizard user) { if (numWizards < NUM_WIZARDS_ALLOWED) { - tower.enter(wizard); + tower.enter(user); numWizards++; } else { - LOGGER.info("{} is not allowed to enter!", wizard); + LOGGER.info("{} is not allowed to enter!", user); } } } @@ -102,11 +102,11 @@ And here is tower entering scenario ``` WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); -proxy.enter(new Wizard("Red wizard")); // Red wizard enters the tower. -proxy.enter(new Wizard("White wizard")); // White wizard enters the tower. -proxy.enter(new Wizard("Black wizard")); // Black wizard enters the tower. -proxy.enter(new Wizard("Green wizard")); // Green wizard is not allowed to enter! -proxy.enter(new Wizard("Brown wizard")); // Brown wizard is not allowed to enter! +proxy.enter(new Wizard("Red user")); // Red user enters the tower. +proxy.enter(new Wizard("White user")); // White user enters the tower. +proxy.enter(new Wizard("Black user")); // Black user enters the tower. +proxy.enter(new Wizard("Green user")); // Green user is not allowed to enter! +proxy.enter(new Wizard("Brown user")); // Brown user is not allowed to enter! ``` ## Applicability diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java deleted file mode 100644 index ce5637214a6f..000000000000 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.proxy; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@link Wizard} - */ -public class WizardTest { - - @Test - public void testToString() throws Exception { - final String[] wizardNames = {"Gandalf", "Dumbledore", "Oz", "Merlin"}; - for (String name : wizardNames) { - assertEquals(name, new Wizard(name).toString()); - } - } -} \ No newline at end of file diff --git a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java index 2958376d6755..96c8a12e0f45 100644 --- a/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java +++ b/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -49,6 +49,8 @@ public void tearDown() { @Test public void testEnter() throws Exception { + + // Given final Wizard[] wizards = new Wizard[]{ new Wizard("Gandalf"), new Wizard("Dumbledore"), @@ -56,11 +58,13 @@ public void testEnter() throws Exception { new Wizard("Merlin") }; + // When final WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); for (Wizard wizard : wizards) { proxy.enter(wizard); } + // Then assertTrue(appender.logContains("Gandalf enters the tower.")); assertTrue(appender.logContains("Dumbledore enters the tower.")); assertTrue(appender.logContains("Oz enters the tower.")); diff --git a/singleton/src/main/java/com/iluwatar/singleton/App.java b/singleton/src/main/java/com/iluwatar/singleton/App.java index 377c56cca8bf..15142a118bee 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/App.java +++ b/singleton/src/main/java/com/iluwatar/singleton/App.java @@ -78,13 +78,7 @@ public static void main(String[] args) { LOGGER.info("ivoryTower1={}", ivoryTower1); LOGGER.info("ivoryTower2={}", ivoryTower2); - // lazily initialized singleton - ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower1 = - ThreadSafeLazyLoadedIvoryTower.getInstance(); - ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower2 = - ThreadSafeLazyLoadedIvoryTower.getInstance(); - LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); - LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); + // enum singleton EnumIvoryTower enumIvoryTower1 = EnumIvoryTower.INSTANCE; @@ -98,12 +92,6 @@ public static void main(String[] args) { ThreadSafeDoubleCheckLocking dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl2.toString()); - // initialize on demand holder idiom - InitializingOnDemandHolderIdiom demandHolderIdiom = - InitializingOnDemandHolderIdiom.getInstance(); - LOGGER.info(demandHolderIdiom.toString()); - InitializingOnDemandHolderIdiom demandHolderIdiom2 = - InitializingOnDemandHolderIdiom.getInstance(); - LOGGER.info(demandHolderIdiom2.toString()); + } } diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java deleted file mode 100644 index 64252fb5ba26..000000000000 --- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.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). - * - */ -public final class InitializingOnDemandHolderIdiom { - - /** - * Private constructor. - */ - private InitializingOnDemandHolderIdiom() {} - - /** - * @return Singleton instance - */ - public static InitializingOnDemandHolderIdiom getInstance() { - return HelperHolder.INSTANCE; - } - - /** - * Provides the lazy-loaded Singleton instance. - */ - private static class HelperHolder { - private static final InitializingOnDemandHolderIdiom INSTANCE = - new InitializingOnDemandHolderIdiom(); - } -} diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java deleted file mode 100644 index 68f190d4681f..000000000000 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.singleton; - -/** - * 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 - */ -public final class ThreadSafeLazyLoadedIvoryTower { - - private static ThreadSafeLazyLoadedIvoryTower instance; - - private ThreadSafeLazyLoadedIvoryTower() { - // to prevent instantiating by Reflection call - if (instance != null) { - throw new IllegalStateException("Already initialized."); - } - } - - /** - * The instance gets created only when it is called for first time. Lazy-loading - */ - public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() { - - if (instance == null) { - instance = new ThreadSafeLazyLoadedIvoryTower(); - } - - return instance; - } -} diff --git a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java index e6427a75386e..98bbf12a39bd 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java @@ -32,8 +32,9 @@ public class EnumIvoryTowerTest extends SingletonTest { /** * Create a new singleton test instance using the given 'getInstance' method */ - public EnumIvoryTowerTest() { + public EnumIvoryTowerTest() throws Exception { super(() -> EnumIvoryTower.INSTANCE); + testMultipleCallsReturnTheSameObjectInSameThread(); } } diff --git a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java b/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java deleted file mode 100644 index 763e21d80a4f..000000000000 --- a/singleton/src/test/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiomTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.singleton; - -/** - * Date: 12/29/15 - 19:22 PM - * - * @author Jeroen Meulemeester - */ -public class InitializingOnDemandHolderIdiomTest extends SingletonTest { - - /** - * Create a new singleton test instance using the given 'getInstance' method - */ - public InitializingOnDemandHolderIdiomTest() { - super(InitializingOnDemandHolderIdiom::getInstance); - } - -} \ No newline at end of file diff --git a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java index 770df5638136..6bba87b5c5c7 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/IvoryTowerTest.java @@ -32,8 +32,9 @@ public class IvoryTowerTest extends SingletonTest { /** * Create a new singleton test instance using the given 'getInstance' method */ - public IvoryTowerTest() { + public IvoryTowerTest() throws Exception { super(IvoryTower::getInstance); + testMultipleCallsReturnTheSameObjectInDifferentThreads(); } } \ No newline at end of file diff --git a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java index f468ad0b8e6b..3cf0e566caf9 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -87,6 +87,8 @@ public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exce final List> tasks = new ArrayList<>(); for (int i = 0; i < 10000; i++) { tasks.add(this.singletonInstanceMethod::get); + + } // Use up to 8 concurrent threads to handle the tasks diff --git a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java index 1d00d9f8f624..9e521f70ba70 100644 --- a/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java +++ b/singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java @@ -32,8 +32,9 @@ public class ThreadSafeDoubleCheckLockingTest extends SingletonTest { - - /** - * Create a new singleton test instance using the given 'getInstance' method - */ - public ThreadSafeLazyLoadedIvoryTowerTest() { - super(ThreadSafeLazyLoadedIvoryTower::getInstance); - } - -} diff --git a/state/etc/state.ucls b/state/etc/state.ucls index e0be8d7127e6..e6ca6f45b77e 100644 --- a/state/etc/state.ucls +++ b/state/etc/state.ucls @@ -5,7 +5,7 @@ file="/state/src/main/java/com/iluwatar/state/AngryState.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -14,7 +14,7 @@ file="/state/src/main/java/com/iluwatar/state/PeacefulState.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -23,7 +23,7 @@ file="/state/src/main/java/com/iluwatar/state/State.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -32,7 +32,7 @@ file="/state/src/main/java/com/iluwatar/state/Mammoth.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -72,7 +72,7 @@ + sort-features="false" accessors="true" mobility="true"> diff --git a/state/src/test/java/com/iluwatar/state/MammothTest.java b/state/src/test/java/com/iluwatar/state/MammothTest.java index 60f4b18f47f4..a633c2b7ae12 100644 --- a/state/src/test/java/com/iluwatar/state/MammothTest.java +++ b/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -61,28 +61,35 @@ public void tearDown() { */ @Test public void testTimePasses() { - final Mammoth mammoth = new Mammoth(); + // given + final Mammoth mammoth = new Mammoth(); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(1 , appender.getLogSize()); + // when mammoth.timePasses(); assertEquals("The mammoth gets angry!", appender.getLastMessage()); assertEquals(2 , appender.getLogSize()); + // then mammoth.observe(); assertEquals("The mammoth is furious!", appender.getLastMessage()); assertEquals(3 , appender.getLogSize()); + // when mammoth.timePasses(); assertEquals("The mammoth calms down.", appender.getLastMessage()); assertEquals(4 , appender.getLogSize()); + // then mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(5 , appender.getLogSize()); + // TODO Add stress state + } /** diff --git a/strategy/etc/strategy.ucls b/strategy/etc/strategy.ucls index 9eba0241764c..d29c4181c78e 100644 --- a/strategy/etc/strategy.ucls +++ b/strategy/etc/strategy.ucls @@ -5,7 +5,7 @@ file="/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -14,7 +14,7 @@ file="/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -23,7 +23,7 @@ file="/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -32,7 +32,7 @@ file="/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -41,7 +41,7 @@ file="/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java" binary="false" corner="BOTTOM_RIGHT"> + sort-features="false" accessors="true" mobility="true"> @@ -67,7 +67,7 @@ + sort-features="false" accessors="true" mobility="true"> diff --git a/strategy/src/main/java/com/iluwatar/strategy/App.java b/strategy/src/main/java/com/iluwatar/strategy/App.java deleted file mode 100644 index 00b2eeaad876..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/App.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * 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. - * - */ -public class App { - - private static final Logger LOGGER = LoggerFactory.getLogger(App.class); - - /** - * 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()); - dragonSlayer.goToBattle(); - LOGGER.info("Red dragon emerges."); - dragonSlayer.changeStrategy(new ProjectileStrategy()); - dragonSlayer.goToBattle(); - LOGGER.info("Black dragon lands before you."); - dragonSlayer.changeStrategy(new SpellStrategy()); - dragonSlayer.goToBattle(); - - // Java 8 Strategy pattern - LOGGER.info("Green dragon spotted ahead!"); - dragonSlayer = new DragonSlayer( - () -> LOGGER.info("With your Excalibur you severe the dragon's head!")); - dragonSlayer.goToBattle(); - LOGGER.info("Red dragon emerges."); - dragonSlayer.changeStrategy(() -> LOGGER.info( - "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); - dragonSlayer.goToBattle(); - LOGGER.info("Black dragon lands before you."); - dragonSlayer.changeStrategy(() -> LOGGER.info( - "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); - dragonSlayer.goToBattle(); - } -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java deleted file mode 100644 index 8c31faee00d8..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -/** - * - * DragonSlayer uses different strategies to slay the dragon. - * - */ -public class DragonSlayer { - - private DragonSlayingStrategy strategy; - - public DragonSlayer(DragonSlayingStrategy strategy) { - this.strategy = strategy; - } - - public void changeStrategy(DragonSlayingStrategy strategy) { - this.strategy = strategy; - } - - public void goToBattle() { - strategy.execute(); - } -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java deleted file mode 100644 index 28e0a19bf990..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -/** - * - * Strategy interface. - * - */ -@FunctionalInterface -public interface DragonSlayingStrategy { - - void execute(); - -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java deleted file mode 100644 index 24c35edc7358..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Melee strategy. - * - */ -public class MeleeStrategy implements DragonSlayingStrategy { - - private static final Logger LOGGER = LoggerFactory.getLogger(MeleeStrategy.class); - - @Override - public void execute() { - LOGGER.info("With your Excalibur you sever the dragon's head!"); - } -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java deleted file mode 100644 index c42badd5cb1e..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Projectile strategy. - * - */ -public class ProjectileStrategy implements DragonSlayingStrategy { - - private static final Logger LOGGER = LoggerFactory.getLogger(ProjectileStrategy.class); - - @Override - public void execute() { - LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); - } -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java b/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java deleted file mode 100644 index 12c0f8323d5b..000000000000 --- a/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Spell strategy. - * - */ -public class SpellStrategy implements DragonSlayingStrategy { - - private static final Logger LOGGER = LoggerFactory.getLogger(SpellStrategy.class); - - @Override - public void execute() { - LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); - } - -} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmani.java b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmani.java new file mode 100755 index 000000000000..f075641d456e --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmani.java @@ -0,0 +1,29 @@ +package com.iluwatar.strategy.own; + +public abstract class ITUzmani { + KodYazabilme kodYazabilme; + TestEdebilme testEdebilme; + + public ITUzmani() { + } + + public void setKodYazabilme(KodYazabilme kodYazabilme) { + this.kodYazabilme = kodYazabilme; + } + + public void setTestEdebilme(TestEdebilme testEdebilme) { + this.testEdebilme = testEdebilme; + } + + abstract void display(); + + public void kodlayabilirMisin() { + kodYazabilme.kodla(); + } + + public void testYapabilirMisin() { + testEdebilme.testEt(); + } + + +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniAyse.java b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniAyse.java new file mode 100755 index 000000000000..0b37a40849a5 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniAyse.java @@ -0,0 +1,18 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ITUzmaniAyse extends ITUzmani { + + private static final Logger LOGGER = LoggerFactory.getLogger(ITUzmaniAyse.class); + + public ITUzmaniAyse() { + kodYazabilme = new Kodlayamazki(); + testEdebilme = new TestUzmaniSenior(); + } + + public void display() { + LOGGER.info("Merhaba Ben Ayse"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniBerkay.java b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniBerkay.java new file mode 100755 index 000000000000..bddf31c8e386 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/ITUzmaniBerkay.java @@ -0,0 +1,16 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ITUzmaniBerkay extends ITUzmani { + + private static final Logger LOGGER = LoggerFactory.getLogger(ITUzmaniBerkay.class); + public ITUzmaniBerkay() { + setKodYazabilme(new KodcuJunior()); + setTestEdebilme(new TestEdemezki()); + } + public void display() { + LOGGER.info("Ben Berkay..."); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/KodYazabilme.java b/strategy/src/main/java/com/iluwatar/strategy/own/KodYazabilme.java new file mode 100755 index 000000000000..581bca9d388b --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/KodYazabilme.java @@ -0,0 +1,5 @@ +package com.iluwatar.strategy.own; + +public interface KodYazabilme { + public void kodla(); +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/KodcuJunior.java b/strategy/src/main/java/com/iluwatar/strategy/own/KodcuJunior.java new file mode 100755 index 000000000000..f9218e06da9f --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/KodcuJunior.java @@ -0,0 +1,13 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class KodcuJunior implements KodYazabilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(KodcuJunior.class); + + public void kodla() { + LOGGER.info("Kodcuyum, yeni sayilirim ama yetenekliyim, yazarim!!"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/KodcuSenior.java b/strategy/src/main/java/com/iluwatar/strategy/own/KodcuSenior.java new file mode 100755 index 000000000000..c39d4ad35b46 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/KodcuSenior.java @@ -0,0 +1,12 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class KodcuSenior implements KodYazabilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(KodcuSenior.class); + public void kodla() { + LOGGER.info("Deli gibi kodlarim ,Senior kişiyim..."); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/Kodlayamazki.java b/strategy/src/main/java/com/iluwatar/strategy/own/Kodlayamazki.java new file mode 100755 index 000000000000..fb7d71950837 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/Kodlayamazki.java @@ -0,0 +1,13 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Kodlayamazki implements KodYazabilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(Kodlayamazki.class); + + public void kodla() { + LOGGER.info("Kodlamak !! ; o ne nedir ?"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/Sirket.java b/strategy/src/main/java/com/iluwatar/strategy/own/Sirket.java new file mode 100755 index 000000000000..efc201ffea1d --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/Sirket.java @@ -0,0 +1,20 @@ +package com.iluwatar.strategy.own; + +public class Sirket { + + public static void main(String[] args) { + + ITUzmaniBerkay uzmanBerkay = new ITUzmaniBerkay(); + ITUzmaniAyse uzmanAyse = new ITUzmaniAyse(); + + uzmanBerkay.display(); + uzmanBerkay.kodlayabilirMisin(); + uzmanBerkay.testYapabilirMisin(); + + + uzmanAyse.display(); + uzmanAyse.kodlayabilirMisin(); + uzmanAyse.setKodYazabilme(new KodcuSenior()); // egitim almis ve senior kisiye donusmus + uzmanAyse.kodlayabilirMisin(); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/TestEdebilme.java b/strategy/src/main/java/com/iluwatar/strategy/own/TestEdebilme.java new file mode 100755 index 000000000000..9b3486f2a0d0 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/TestEdebilme.java @@ -0,0 +1,5 @@ +package com.iluwatar.strategy.own; + +public interface TestEdebilme { + public void testEt(); +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/TestEdemezki.java b/strategy/src/main/java/com/iluwatar/strategy/own/TestEdemezki.java new file mode 100755 index 000000000000..dd1b29aa3eba --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/TestEdemezki.java @@ -0,0 +1,13 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestEdemezki implements TestEdebilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestEdemezki.class); + + public void testEt() { + LOGGER.info("Ben teste bulasmam abi..."); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniJunior.java b/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniJunior.java new file mode 100755 index 000000000000..64bf2ce45691 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniJunior.java @@ -0,0 +1,13 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestUzmaniJunior implements TestEdebilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestUzmaniJunior.class); + + public void testEt() { + LOGGER.info("Test isinde yeniyim ama gencim, test ederim"); + } +} diff --git a/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniSenior.java b/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniSenior.java new file mode 100755 index 000000000000..f5b3ee2a9438 --- /dev/null +++ b/strategy/src/main/java/com/iluwatar/strategy/own/TestUzmaniSenior.java @@ -0,0 +1,12 @@ +package com.iluwatar.strategy.own; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestUzmaniSenior implements TestEdebilme { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestUzmaniSenior.class); + public void testEt() { + LOGGER.info("Test uzmaniyim, projeyi getirin test edeyim"); + } +} diff --git a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/strategy/src/test/java/com/iluwatar/strategy/AppTest.java deleted file mode 100644 index 59b3a22a954e..000000000000 --- a/strategy/src/test/java/com/iluwatar/strategy/AppTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.junit.Test; - -/** - * - * Application test - * - */ -public class AppTest { - - @Test - public void test() { - String[] args = {}; - App.main(args); - } -} diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java deleted file mode 100644 index ad8b9784fe4d..000000000000 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -/** - * Date: 12/29/15 - 10:50 PM - * - * @author Jeroen Meulemeester - */ -public class DragonSlayerTest { - - /** - * Verify if the dragon slayer uses the strategy during battle - */ - @Test - public void testGoToBattle() { - final DragonSlayingStrategy strategy = mock(DragonSlayingStrategy.class); - final DragonSlayer dragonSlayer = new DragonSlayer(strategy); - - dragonSlayer.goToBattle(); - verify(strategy).execute(); - verifyNoMoreInteractions(strategy); - } - - /** - * Verify if the dragon slayer uses the new strategy during battle after a change of strategy - */ - @Test - public void testChangeStrategy() throws Exception { - final DragonSlayingStrategy initialStrategy = mock(DragonSlayingStrategy.class); - final DragonSlayer dragonSlayer = new DragonSlayer(initialStrategy); - - dragonSlayer.goToBattle(); - verify(initialStrategy).execute(); - - final DragonSlayingStrategy newStrategy = mock(DragonSlayingStrategy.class); - dragonSlayer.changeStrategy(newStrategy); - - dragonSlayer.goToBattle(); - verify(newStrategy).execute(); - - verifyNoMoreInteractions(initialStrategy, newStrategy); - } -} \ No newline at end of file diff --git a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java deleted file mode 100644 index 52e596e5c158..000000000000 --- a/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.strategy; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * Date: 12/29/15 - 10:58 PM - * - * @author Jeroen Meulemeester - */ -@RunWith(Parameterized.class) -public class DragonSlayingStrategyTest { - - /** - * @return The test parameters for each cycle - */ - @Parameterized.Parameters - public static Collection data() { - 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!" - } - ); - } - - /** - * The tested strategy - */ - private final DragonSlayingStrategy strategy; - - /** - * The expected action in the log - */ - private final String expectedResult; - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(); - } - - @After - public void tearDown() { - appender.stop(); - } - - - /** - * Create a new test instance for the given strategy - * - * @param strategy The tested strategy - * @param expectedResult The expected result - */ - public DragonSlayingStrategyTest(final DragonSlayingStrategy strategy, final String expectedResult) { - this.strategy = strategy; - this.expectedResult = expectedResult; - } - - /** - * Test if executing the strategy gives the correct response - */ - @Test - public void testExecute() { - this.strategy.execute(); - assertEquals(this.expectedResult, appender.getLastMessage()); - assertEquals(1, appender.getLogSize()); - } - - private class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); - - public InMemoryAppender() { - ((Logger) LoggerFactory.getLogger("root")).addAppender(this); - start(); - } - - @Override - protected void append(ILoggingEvent eventObject) { - log.add(eventObject); - } - - public int getLogSize() { - return log.size(); - } - - public String getLastMessage() { - return log.get(log.size() - 1).getFormattedMessage(); - } - } -} diff --git a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/strategy/src/test/java/com/iluwatar/strategy/KodcuTest.java similarity index 62% rename from bridge/src/test/java/com/iluwatar/bridge/HammerTest.java rename to strategy/src/test/java/com/iluwatar/strategy/KodcuTest.java index a650bae04d62..849aa0a14037 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java +++ b/strategy/src/test/java/com/iluwatar/strategy/KodcuTest.java @@ -20,26 +20,50 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.bridge; +package com.iluwatar.strategy; +import com.iluwatar.strategy.own.ITUzmani; +import com.iluwatar.strategy.own.ITUzmaniAyse; +import com.iluwatar.strategy.own.KodYazabilme; +import com.iluwatar.strategy.own.KodcuSenior; import org.junit.Test; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; /** - * Tests for hammer + * Date: 12/29/16 - 10:50 PM + * + * @author Altug Bilgin Altintas */ -public class HammerTest extends WeaponTest { +public class KodcuTest { /** - * Invoke all possible actions on the weapon and check if the actions are executed on the actual - * underlying weapon implementation. + * Verify if the kodcu uses the strategy during coding */ @Test - public void testHammer() throws Exception { - final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class))); - testBasicWeaponActions(hammer); + public void testKodYazabilme() { + + // given + final KodYazabilme kodcuSenior = mock(KodcuSenior.class); + final ITUzmani ayse = new ITUzmaniAyse(); + + // when + ayse.setKodYazabilme(kodcuSenior); + ayse.kodlayabilirMisin(); + + // then + verify(kodcuSenior).kodla(); + + } + + @Test + public void testTestEdebilme() { + //... TODO + } + + + } \ No newline at end of file diff --git a/template-method/README.md b/template-method/README.md index ad972f06bce5..627afd1c826f 100644 --- a/template-method/README.md +++ b/template-method/README.md @@ -15,7 +15,7 @@ Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. -![alt text](./etc/template-method_1.png "Template Method") + ## Applicability The Template Method pattern should be used diff --git a/template-method/etc/template-method.ucls b/template-method/etc/template-method.ucls index ec0ce620a3ae..d4e4b2509c60 100644 --- a/template-method/etc/template-method.ucls +++ b/template-method/etc/template-method.ucls @@ -1,42 +1,42 @@ - + sort-features="false" accessors="true" mobility="true"> - + sort-features="false" accessors="true" mobility="true"> - + sort-features="false" accessors="true" mobility="true"> - + sort-features="false" accessors="true" mobility="true"> @@ -58,7 +58,7 @@ + sort-features="false" accessors="true" mobility="true"> 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 5ad51d3e5893..50060bc1cc6d 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/App.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/App.java @@ -27,8 +27,8 @@ * Template Method defines a skeleton for an algorithm. The algorithm subclasses provide * implementation for the blank parts. *

- * In this example {@link HalflingThief} contains {@link StealingMethod} that can be changed. First - * the thief hits with {@link HitAndRunMethod} and then with {@link SubtleMethod}. + * In this example {@link Engineer} contains {@link EngineeringMethod} that can be changed. First + * the thief hits with {@link MicroServicesMethod} and then with {@link MonolithicMethod}. * */ public class App { @@ -39,9 +39,10 @@ public class App { * @param args command line args */ public static void main(String[] args) { - HalflingThief thief = new HalflingThief(new HitAndRunMethod()); - thief.steal(); - thief.changeMethod(new SubtleMethod()); - thief.steal(); + Engineer engineer = new Engineer(new MicroServicesMethod()); + engineer.justDoIt(); + + engineer.changeMethod(new MonolithicMethod()); + engineer.justDoIt(); } } diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java b/template-method/src/main/java/com/iluwatar/templatemethod/Engineer.java similarity index 82% rename from template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java rename to template-method/src/main/java/com/iluwatar/templatemethod/Engineer.java index 0b1fb044ee6c..03f2a5d63626 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/HalflingThief.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/Engineer.java @@ -24,22 +24,22 @@ /** * - * Halfling thief uses {@link StealingMethod} to steal. + * Halfling thief uses {@link EngineeringMethod} to doIt. * */ -public class HalflingThief { +public class Engineer { - private StealingMethod method; + private EngineeringMethod method; - public HalflingThief(StealingMethod method) { + public Engineer(EngineeringMethod method) { this.method = method; } - public void steal() { - method.steal(); + public void justDoIt() { + method.doIt(); } - public void changeMethod(StealingMethod method) { + public void changeMethod(EngineeringMethod method) { this.method = method; } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java b/template-method/src/main/java/com/iluwatar/templatemethod/EngineeringMethod.java similarity index 70% rename from decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java rename to template-method/src/main/java/com/iluwatar/templatemethod/EngineeringMethod.java index 5d5e0518381d..3a4111398533 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/SimpleTroll.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/EngineeringMethod.java @@ -20,32 +20,33 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.decorator; +package com.iluwatar.templatemethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * - * SimpleTroll implements {@link Troll} interface directly. - * + * Engineering Method defines skeleton for the algorithm. + * */ -public class SimpleTroll implements Troll { +public abstract class EngineeringMethod { - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTroll.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EngineeringMethod.class); - @Override - public void attack() { - LOGGER.info("The troll tries to grab you!"); - } + protected abstract String plan(); - @Override - public int getAttackPower() { - return 10; - } + protected abstract void check(String plan); + + protected abstract void act(String plan); - @Override - public void fleeBattle() { - LOGGER.info("The troll shrieks in horror and runs away!"); + /** + * Steal + */ + public void doIt() { + String plan = plan(); + LOGGER.info("Planned job executed :" + plan); + check(plan); + act(plan); } } diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/MicroServicesMethod.java similarity index 72% rename from template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java rename to template-method/src/main/java/com/iluwatar/templatemethod/MicroServicesMethod.java index 0b7ff9d911cc..bfbec03c0e46 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/HitAndRunMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/MicroServicesMethod.java @@ -27,25 +27,25 @@ /** * - * HitAndRunMethod implementation of {@link StealingMethod}. + * MicroServicesMethod implementation of {@link EngineeringMethod}. * */ -public class HitAndRunMethod extends StealingMethod { +public class MicroServicesMethod extends EngineeringMethod { - private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MicroServicesMethod.class); @Override - protected String pickTarget() { - return "old goblin woman"; + protected String plan() { + return "Define all old services"; } @Override - protected void confuseTarget(String target) { - LOGGER.info("Approach the {} from behind.", target); + protected void check(String plan) { + LOGGER.info("Control all microservices are working correctly", plan); } @Override - protected void stealTheItem(String target) { - LOGGER.info("Grab the handbag and run away fast!"); + protected void act(String plan) { + LOGGER.info("New Standard : make new services as a microservices"); } } diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/MonolithicMethod.java similarity index 69% rename from template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java rename to template-method/src/main/java/com/iluwatar/templatemethod/MonolithicMethod.java index d8b16af3dab4..687959ee57ac 100644 --- a/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java +++ b/template-method/src/main/java/com/iluwatar/templatemethod/MonolithicMethod.java @@ -27,25 +27,25 @@ /** * - * SubtleMethod implementation of {@link StealingMethod}. + * MonolithicMethod implementation of {@link EngineeringMethod}. * */ -public class SubtleMethod extends StealingMethod { +public class MonolithicMethod extends EngineeringMethod { - private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MonolithicMethod.class); @Override - protected String pickTarget() { - return "shop keeper"; + protected String plan() { + return "Define hardware need in order to run this giant Monolithic system"; } @Override - protected void confuseTarget(String target) { - LOGGER.info("Approach the {} with tears running and hug him!", target); + protected void check(String plan) { + LOGGER.info("Check if Monolithic system do not use %80 of the resources", plan); } @Override - protected void stealTheItem(String target) { - LOGGER.info("While in close contact grab the {}'s wallet.", target); + protected void act(String plan) { + LOGGER.info("New Standard : Adapt new services in to Monolithic system", plan); } } diff --git a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java b/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java deleted file mode 100644 index 61aaf4ab4562..000000000000 --- a/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.templatemethod; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * StealingMethod defines skeleton for the algorithm. - * - */ -public abstract class StealingMethod { - - private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class); - - protected abstract String pickTarget(); - - protected abstract void confuseTarget(String target); - - protected abstract void stealTheItem(String target); - - /** - * Steal - */ - public void steal() { - String target = pickTarget(); - LOGGER.info("The target has been chosen as {}.", target); - confuseTarget(target); - stealTheItem(target); - } -} diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/EngineerTest.java similarity index 64% rename from template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java rename to template-method/src/test/java/com/iluwatar/templatemethod/EngineerTest.java index 6cc80446c0d2..69ab27b53d54 100644 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java +++ b/template-method/src/test/java/com/iluwatar/templatemethod/EngineerTest.java @@ -31,41 +31,53 @@ /** * Date: 12/29/15 - 18:15 PM * - * @author Jeroen Meulemeester + * @author @altugaltintas */ -public class HalflingThiefTest { +public class EngineerTest { /** - * Verify if the thief uses the provided stealing method + * Verify if the engineer uses the provided engineering method */ @Test - public void testSteal() { - final StealingMethod method = mock(StealingMethod.class); - final HalflingThief thief = new HalflingThief(method); + public void testDoIt() { - thief.steal(); - verify(method).steal(); + // Given + final EngineeringMethod method = mock(EngineeringMethod.class); + final Engineer engineer = new Engineer(method); + // When + engineer.justDoIt(); + + // Then + verify(method).doIt(); verifyNoMoreInteractions(method); } /** - * Verify if the thief uses the provided stealing method, and the new method after changing it + * Verify if the engineer uses the provided doIT method, and the new method after changing it */ @Test public void testChangeMethod() { - final StealingMethod initialMethod = mock(StealingMethod.class); - final HalflingThief thief = new HalflingThief(initialMethod); - thief.steal(); - verify(initialMethod).steal(); + // Given + final EngineeringMethod initialMethod = mock(EngineeringMethod.class); + final Engineer engineer = new Engineer(initialMethod); + + // When + engineer.justDoIt(); + + // Then + verify(initialMethod).doIt(); - final StealingMethod newMethod = mock(StealingMethod.class); - thief.changeMethod(newMethod); + // Given + final EngineeringMethod newMethod = mock(EngineeringMethod.class); - thief.steal(); - verify(newMethod).steal(); + // When + engineer.changeMethod(newMethod); + engineer.justDoIt(); + // Then + verify(newMethod).doIt(); verifyNoMoreInteractions(initialMethod, newMethod); } diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java deleted file mode 100644 index 3bc7b28b49c9..000000000000 --- a/template-method/src/test/java/com/iluwatar/templatemethod/HitAndRunMethodTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.templatemethod; - -/** - * Date: 12/30/15 - 18:12 PM - * - * @author Jeroen Meulemeester - */ -public class HitAndRunMethodTest extends StealingMethodTest { - - /** - * Create a new test for the {@link HitAndRunMethod} - */ - public HitAndRunMethodTest() { - super( - new HitAndRunMethod(), - "old goblin woman", - "The target has been chosen as old goblin woman.", - "Approach the old goblin woman from behind.", - "Grab the handbag and run away fast!" - ); - } - -} \ No newline at end of file diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java deleted file mode 100644 index 98ac62613e2c..000000000000 --- a/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.templatemethod; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import java.util.LinkedList; -import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -/** - * Date: 12/30/15 - 18:12 PM - * @param Type of StealingMethod - * @author Jeroen Meulemeester - */ -public abstract class StealingMethodTest { - - private InMemoryAppender appender; - - @Before - public void setUp() { - appender = new InMemoryAppender(); - } - - @After - public void tearDown() { - appender.stop(); - } - - /** - * The tested stealing method - */ - private final M method; - - /** - * The expected target - */ - private final String expectedTarget; - - /** - * The expected target picking result - */ - private final String expectedTargetResult; - - /** - * The expected confusion method - */ - private final String expectedConfuseMethod; - - /** - * The expected stealing method - */ - private final String expectedStealMethod; - - /** - * Create a new test for the given stealing method, together with the expected results - * - * @param method The tested stealing method - * @param expectedTarget The expected target name - * @param expectedTargetResult The expected target picking result - * @param expectedConfuseMethod The expected confusion method - * @param expectedStealMethod The expected stealing method - */ - public StealingMethodTest(final M method, String expectedTarget, final String expectedTargetResult, - final String expectedConfuseMethod, final String expectedStealMethod) { - - this.method = method; - this.expectedTarget = expectedTarget; - this.expectedTargetResult = expectedTargetResult; - this.expectedConfuseMethod = expectedConfuseMethod; - this.expectedStealMethod = expectedStealMethod; - } - - /** - * Verify if the thief picks the correct target - */ - @Test - public void testPickTarget() { - assertEquals(expectedTarget, this.method.pickTarget()); - } - - /** - * Verify if the target confusing step goes as planned - */ - @Test - public void testConfuseTarget() { - assertEquals(0, appender.getLogSize()); - - this.method.confuseTarget(this.expectedTarget); - assertEquals(this.expectedConfuseMethod, appender.getLastMessage()); - assertEquals(1, appender.getLogSize()); - } - - /** - * Verify if the stealing step goes as planned - */ - @Test - public void testStealTheItem() { - assertEquals(0, appender.getLogSize()); - - this.method.stealTheItem(this.expectedTarget); - assertEquals(this.expectedStealMethod, appender.getLastMessage()); - assertEquals(1, appender.getLogSize()); - } - - /** - * Verify if the complete steal process goes as planned - */ - @Test - public void testSteal() { - this.method.steal(); - - assertTrue(appender.logContains(this.expectedTargetResult)); - assertTrue(appender.logContains(this.expectedConfuseMethod)); - assertTrue(appender.logContains(this.expectedStealMethod)); - assertEquals(3, appender.getLogSize()); - } - - private class InMemoryAppender extends AppenderBase { - private List log = new LinkedList<>(); - - public InMemoryAppender() { - ((Logger) LoggerFactory.getLogger("root")).addAppender(this); - start(); - } - - @Override - protected void append(ILoggingEvent eventObject) { - log.add(eventObject); - } - - public int getLogSize() { - return log.size(); - } - - public String getLastMessage() { - return log.get(log.size() - 1).getFormattedMessage(); - } - - public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); - } - } -} diff --git a/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java b/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java deleted file mode 100644 index 41105c43e42d..000000000000 --- a/template-method/src/test/java/com/iluwatar/templatemethod/SubtleMethodTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * The MIT License - * Copyright (c) 2014-2016 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.templatemethod; - -/** - * Date: 12/30/15 - 18:19 PM - * - * @author Jeroen Meulemeester - */ -public class SubtleMethodTest extends StealingMethodTest { - - /** - * Create a new test for the {@link SubtleMethod} - */ - public SubtleMethodTest() { - super( - new SubtleMethod(), - "shop keeper", - "The target has been chosen as shop keeper.", - "Approach the shop keeper with tears running and hug him!", - "While in close contact grab the shop keeper's wallet." - ); - } - -} \ No newline at end of file