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
+
+
**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.
-
+
## 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.
-```
+
+
## 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.
-
+
## 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