repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
java-design-patterns
java-design-patterns-master/currying/src/main/java/com/iluwatar/currying/Book.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.currying; import java.time.LocalDate; import java.util.Objects; import java.util.function.Function; import lombok.AllArgsConstructor; /** * Book class. */ @AllArgsConstructor public class Book { private final Genre genre; private final String author; private final String title; private final LocalDate publicationDate; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; return Objects.equals(author, book.author) && Objects.equals(genre, book.genre) && Objects.equals(title, book.title) && Objects.equals(publicationDate, book.publicationDate); } @Override public int hashCode() { return Objects.hash(author, genre, title, publicationDate); } @Override public String toString() { return "Book{" + "genre=" + genre + ", author='" + author + '\'' + ", title='" + title + '\'' + ", publicationDate=" + publicationDate + '}'; } /** * Curried book builder/creator function. */ static Function<Genre, Function<String, Function<String, Function<LocalDate, Book>>>> book_creator = bookGenre -> bookAuthor -> bookTitle -> bookPublicationDate -> new Book(bookGenre, bookAuthor, bookTitle, bookPublicationDate); /** * Implements the builder pattern using functional interfaces to create a more readable book * creator function. This function is equivalent to the BOOK_CREATOR function. */ public static AddGenre builder() { return genre -> author -> title -> publicationDate -> new Book(genre, author, title, publicationDate); } /** * Functional interface which adds the genre to a book. */ public interface AddGenre { Book.AddAuthor withGenre(Genre genre); } /** * Functional interface which adds the author to a book. */ public interface AddAuthor { Book.AddTitle withAuthor(String author); } /** * Functional interface which adds the title to a book. */ public interface AddTitle { Book.AddPublicationDate withTitle(String title); } /** * Functional interface which adds the publication date to a book. */ public interface AddPublicationDate { Book withPublicationDate(LocalDate publicationDate); } }
3,758
31.128205
140
java
java-design-patterns
java-design-patterns-master/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.resource.acquisition.is.initialization; import static org.junit.jupiter.api.Assertions.assertTrue; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/28/15 - 9:31 PM * * @author Jeroen Meulemeester */ class ClosableTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } @Test void testOpenClose() { try (final var ignored = new SlidingDoor(); final var ignored1 = new TreasureChest()) { assertTrue(appender.logContains("Sliding door opens.")); assertTrue(appender.logContains("Treasure chest opens.")); } assertTrue(appender.logContains("Treasure chest closes.")); assertTrue(appender.logContains("Sliding door closes.")); } /** * Logging Appender Implementation */ class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().anyMatch(event -> event.getMessage().equals(message)); } } }
2,935
31.622222
140
java
java-design-patterns
java-design-patterns-master/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.resource.acquisition.is.initialization; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,606
38.195122
140
java
java-design-patterns
java-design-patterns-master/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.resource.acquisition.is.initialization; import lombok.extern.slf4j.Slf4j; /** * Resource Acquisition Is Initialization pattern was developed for exception safe resource * management by C++ creator Bjarne Stroustrup. * * <p>In RAII resource is tied to object lifetime: resource allocation is done during object * creation while resource deallocation is done during object destruction. * * <p>In Java RAII is achieved with try-with-resources statement and interfaces {@link * java.io.Closeable} and {@link AutoCloseable}. The try-with-resources statement ensures that each * resource is closed at the end of the statement. Any object that implements {@link * java.lang.AutoCloseable}, which includes all objects which implement {@link java.io.Closeable}, * can be used as a resource. * * <p>In this example, {@link SlidingDoor} implements {@link AutoCloseable} and {@link * TreasureChest} implements {@link java.io.Closeable}. Running the example, we can observe that * both resources are automatically closed. * * <p>http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html */ @Slf4j public class App { /** * Program entry point. */ public static void main(String[] args) throws Exception { try (var ignored = new SlidingDoor()) { LOGGER.info("Walking in."); } try (var ignored = new TreasureChest()) { LOGGER.info("Looting contents."); } } }
2,740
41.169231
140
java
java-design-patterns
java-design-patterns-master/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/SlidingDoor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.resource.acquisition.is.initialization; import lombok.extern.slf4j.Slf4j; /** * SlidingDoor resource. */ @Slf4j public class SlidingDoor implements AutoCloseable { public SlidingDoor() { LOGGER.info("Sliding door opens."); } @Override public void close() { LOGGER.info("Sliding door closes."); } }
1,627
36
140
java
java-design-patterns
java-design-patterns-master/resource-acquisition-is-initialization/src/main/java/com/iluwatar/resource/acquisition/is/initialization/TreasureChest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.resource.acquisition.is.initialization; import java.io.Closeable; import lombok.extern.slf4j.Slf4j; /** * TreasureChest resource. */ @Slf4j public class TreasureChest implements Closeable { public TreasureChest() { LOGGER.info("Treasure chest opens."); } @Override public void close() { LOGGER.info("Treasure chest closes."); } }
1,659
35.888889
140
java
java-design-patterns
java-design-patterns-master/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.trampoline; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test for trampoline pattern. */ class TrampolineAppTest { @Test void testTrampolineWithFactorialFunction() { long result = TrampolineApp.loop(10, 1).result(); assertEquals(3_628_800, result); } }
1,635
37.952381
140
java
java-design-patterns
java-design-patterns-master/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.trampoline; import java.util.stream.Stream; /** * Trampoline pattern allows to define recursive algorithms by iterative loop. * * <p>When get is called on the returned Trampoline, internally it will iterate calling ‘jump’ * on the returned Trampoline as long as the concrete instance returned is {@link * #more(Trampoline)}, stopping once the returned instance is {@link #done(Object)}. * * <p>Essential we convert looping via recursion into iteration, * the key enabling mechanism is the fact that {@link #more(Trampoline)} is a lazy operation. * * @param <T> is type for returning result. */ public interface Trampoline<T> { T get(); /** * Jump to next stage. * * @return next stage */ default Trampoline<T> jump() { return this; } default T result() { return get(); } /** * Checks if complete. * * @return true if complete */ default boolean complete() { return true; } /** * Created a completed Trampoline. * * @param result Completed result * @return Completed Trampoline */ static <T> Trampoline<T> done(final T result) { return () -> result; } /** * Create a Trampoline that has more work to do. * * @param trampoline Next stage in Trampoline * @return Trampoline with more work */ static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) { return new Trampoline<T>() { @Override public boolean complete() { return false; } @Override public Trampoline<T> jump() { return trampoline.result(); } @Override public T get() { return trampoline(this); } T trampoline(final Trampoline<T> trampoline) { return Stream.iterate(trampoline, Trampoline::jump) .filter(Trampoline::complete) .findFirst() .map(Trampoline::result) .get(); } }; } }
3,240
27.9375
140
java
java-design-patterns
java-design-patterns-master/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.trampoline; import lombok.extern.slf4j.Slf4j; /** * Trampoline pattern allows to define recursive algorithms by iterative loop. * * <p>It is possible to implement algorithms recursively in Java without blowing the stack * and to interleave the execution of functions without hard coding them together or even using * threads. */ @Slf4j public class TrampolineApp { /** * Main program for showing pattern. It does loop with factorial function. */ public static void main(String[] args) { LOGGER.info("Start calculating war casualties"); var result = loop(10, 1).result(); LOGGER.info("The number of orcs perished in the war: {}", result); } /** * Manager for pattern. Define it with a factorial function. */ public static Trampoline<Integer> loop(int times, int prod) { if (times == 0) { return Trampoline.done(prod); } else { return Trampoline.more(() -> loop(times - 1, prod * times)); } } }
2,269
36.833333
140
java
java-design-patterns
java-design-patterns-master/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.value.object; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; /** * Unit test for HeroStat. */ class HeroStatTest { /** * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. * * @see <a href="http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html"> * http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/EqualsTester.html * </a> */ @Test void testEquals() { var heroStatA = HeroStat.valueOf(3, 9, 2); var heroStatB = HeroStat.valueOf(3, 9, 2); assertEquals(heroStatA, heroStatB); } /** * The toString() for two equal values must be the same. For two non-equal values it must be * different. */ @Test void testToString() { var heroStatA = HeroStat.valueOf(3, 9, 2); var heroStatB = HeroStat.valueOf(3, 9, 2); var heroStatC = HeroStat.valueOf(3, 9, 8); assertEquals(heroStatA.toString(), heroStatB.toString()); assertNotEquals(heroStatA.toString(), heroStatC.toString()); } }
2,489
37.307692
140
java
java-design-patterns
java-design-patterns-master/value-object/src/test/java/com/iluwatar/value/object/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.value.object; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,591
37.829268
140
java
java-design-patterns
java-design-patterns-master/value-object/src/main/java/com/iluwatar/value/object/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.value.object; import lombok.extern.slf4j.Slf4j; /** * A Value Object are objects which follow value semantics rather than reference semantics. This * means value objects' equality are not based on identity. Two value objects are equal when they * have the same value, not necessarily being the same object.. * * <p>Value Objects must override equals(), hashCode() to check the equality with values. Value * Objects should be immutable so declare members final. Obtain instances by static factory methods. * The elements of the state must be other values, including primitive types. Provide methods, * typically simple getters, to get the elements of the state. A Value Object must check equality * with equals() not == * * <p>For more specific and strict rules to implement value objects check the rules from Stephen * Colebourne's term VALJO : http://blog.joda.org/2014/03/valjos-value-java-objects.html */ @Slf4j public class App { /** * This example creates three HeroStats (value objects) and checks equality between those. */ public static void main(String[] args) { var statA = HeroStat.valueOf(10, 5, 0); var statB = HeroStat.valueOf(10, 5, 0); var statC = HeroStat.valueOf(5, 1, 8); LOGGER.info(statA.toString()); LOGGER.info(statB.toString()); LOGGER.info(statC.toString()); LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); LOGGER.info("Is statA and statC equal : {}", statA.equals(statC)); } }
2,789
44
140
java
java-design-patterns
java-design-patterns-master/value-object/src/main/java/com/iluwatar/value/object/HeroStat.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.value.object; import lombok.Value; /** * HeroStat is a value object. * * @see <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html"> * http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html * </a> */ @Value(staticConstructor = "valueOf") class HeroStat { int strength; int intelligence; int luck; }
1,682
38.139535
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/ShardTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit tests for Shard class. */ class ShardTest { private Data data; private Shard shard; @BeforeEach void setup() { data = new Data(1, "test", Data.DataType.TYPE_1); shard = new Shard(1); } @Test void testStoreData() { try { shard.storeData(data); var field = Shard.class.getDeclaredField("dataStore"); field.setAccessible(true); var dataMap = (Map<Integer, Data>) field.get(shard); assertEquals(1, dataMap.size()); assertEquals(data, dataMap.get(1)); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to modify field access."); } } @Test void testClearData() { try { var dataMap = new HashMap<Integer, Data>(); dataMap.put(1, data); var field = Shard.class.getDeclaredField("dataStore"); field.setAccessible(true); field.set(shard, dataMap); shard.clearData(); dataMap = (HashMap<Integer, Data>) field.get(shard); assertEquals(0, dataMap.size()); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to modify field access."); } } }
2,694
31.865854
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/ShardManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit tests for ShardManager class. */ class ShardManagerTest { private ShardManager shardManager; /** * Initialize shardManager instance. */ @BeforeEach void setup() { shardManager = new TestShardManager(); } @Test void testAddNewShard() { try { var shard = new Shard(1); shardManager.addNewShard(shard); var field = ShardManager.class.getDeclaredField("shardMap"); field.setAccessible(true); var map = (Map<Integer, Shard>) field.get(shardManager); assertEquals(1, map.size()); assertEquals(shard, map.get(1)); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to modify field access."); } } @Test void testRemoveShardById() { try { var shard = new Shard(1); shardManager.addNewShard(shard); boolean flag = shardManager.removeShardById(1); var field = ShardManager.class.getDeclaredField("shardMap"); field.setAccessible(true); var map = (Map<Integer, Shard>) field.get(shardManager); assertTrue(flag); assertEquals(0, map.size()); } catch (IllegalAccessException | NoSuchFieldException e) { fail("Fail to modify field access."); } } @Test void testGetShardById() { var shard = new Shard(1); shardManager.addNewShard(shard); var tmpShard = shardManager.getShardById(1); assertEquals(shard, tmpShard); } static class TestShardManager extends ShardManager { @Override public int storeData(Data data) { return 0; } @Override protected int allocateShard(Data data) { return 0; } } }
3,226
30.637255
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/LookupShardManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit tests for LookupShardManager class. */ class LookupShardManagerTest { private LookupShardManager lookupShardManager; /** * Initialize lookupShardManager instance. */ @BeforeEach void setup() { lookupShardManager = new LookupShardManager(); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); lookupShardManager.addNewShard(shard1); lookupShardManager.addNewShard(shard2); lookupShardManager.addNewShard(shard3); } @Test void testStoreData() { try { var data = new Data(1, "test", Data.DataType.TYPE_1); lookupShardManager.storeData(data); var field = LookupShardManager.class.getDeclaredField("lookupMap"); field.setAccessible(true); var lookupMap = (Map<Integer, Integer>) field.get(lookupShardManager); var shardId = lookupMap.get(1); var shard = lookupShardManager.getShardById(shardId); assertEquals(data, shard.getDataById(1)); } catch (NoSuchFieldException | IllegalAccessException e) { fail("Fail to modify field access."); } } }
2,628
36.028169
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/RangeShardManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit tests for RangeShardManager class. */ class RangeShardManagerTest { private RangeShardManager rangeShardManager; /** * Initialize rangeShardManager instance. */ @BeforeEach void setup() { rangeShardManager = new RangeShardManager(); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); rangeShardManager.addNewShard(shard1); rangeShardManager.addNewShard(shard2); rangeShardManager.addNewShard(shard3); } @Test void testStoreData() { var data = new Data(1, "test", Data.DataType.TYPE_1); rangeShardManager.storeData(data); assertEquals(data, rangeShardManager.getShardById(1).getDataById(1)); } }
2,159
34.409836
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/HashShardManagerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit tests for HashShardManager class. */ class HashShardManagerTest { private HashShardManager hashShardManager; /** * Initialize hashShardManager instance. */ @BeforeEach void setup() { hashShardManager = new HashShardManager(); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); hashShardManager.addNewShard(shard1); hashShardManager.addNewShard(shard2); hashShardManager.addNewShard(shard3); } @Test void testStoreData() { var data = new Data(1, "test", Data.DataType.TYPE_1); hashShardManager.storeData(data); assertEquals(data, hashShardManager.getShardById(1).getDataById(1)); } }
2,147
34.213115
140
java
java-design-patterns
java-design-patterns-master/sharding/src/test/java/com/iluwatar/sharding/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * Unit tests for App class. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,586
36.785714
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/HashShardManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import lombok.extern.slf4j.Slf4j; /** * ShardManager with hash strategy. The purpose of this strategy is to reduce the * chance of hot-spots in the data. It aims to distribute the data across the shards * in a way that achieves a balance between the size of each shard and the average * load that each shard will encounter. */ @Slf4j public class HashShardManager extends ShardManager { @Override public int storeData(Data data) { var shardId = allocateShard(data); var shard = shardMap.get(shardId); shard.storeData(data); LOGGER.info(data.toString() + " is stored in Shard " + shardId); return shardId; } @Override protected int allocateShard(Data data) { var shardCount = shardMap.size(); var hash = data.getKey() % shardCount; return hash == 0 ? hash + shardCount : hash; } }
2,149
38.090909
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; /** * Sharding pattern means dividing a data store into a set of horizontal partitions or shards. This * pattern can improve scalability when storing and accessing large volumes of data. */ public class App { /** * Program main entry point. * * @param args program runtime arguments */ public static void main(String[] args) { var data1 = new Data(1, "data1", Data.DataType.TYPE_1); var data2 = new Data(2, "data2", Data.DataType.TYPE_2); var data3 = new Data(3, "data3", Data.DataType.TYPE_3); var data4 = new Data(4, "data4", Data.DataType.TYPE_1); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); var manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); var rangeShardManager = new RangeShardManager(); rangeShardManager.addNewShard(shard1); rangeShardManager.addNewShard(shard2); rangeShardManager.addNewShard(shard3); rangeShardManager.storeData(data1); rangeShardManager.storeData(data2); rangeShardManager.storeData(data3); rangeShardManager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); var hashShardManager = new HashShardManager(); hashShardManager.addNewShard(shard1); hashShardManager.addNewShard(shard2); hashShardManager.addNewShard(shard3); hashShardManager.storeData(data1); hashShardManager.storeData(data2); hashShardManager.storeData(data3); hashShardManager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); } }
3,165
34.177778
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/LookupShardManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Random; import lombok.extern.slf4j.Slf4j; /** * ShardManager with lookup strategy. In this strategy the sharding logic implements * a map that routes a request for data to the shard that contains that data by using * the shard key. */ @Slf4j public class LookupShardManager extends ShardManager { private final Map<Integer, Integer> lookupMap = new HashMap<>(); @Override public int storeData(Data data) { var shardId = allocateShard(data); lookupMap.put(data.getKey(), shardId); var shard = shardMap.get(shardId); shard.storeData(data); LOGGER.info(data.toString() + " is stored in Shard " + shardId); return shardId; } @Override protected int allocateShard(Data data) { var key = data.getKey(); if (lookupMap.containsKey(key)) { return lookupMap.get(key); } else { var shardCount = shardMap.size(); return new SecureRandom().nextInt(shardCount - 1) + 1; } } }
2,359
35.307692
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/RangeShardManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import lombok.extern.slf4j.Slf4j; /** * ShardManager with range strategy. This strategy groups related items together in the same shard, * and orders them by shard key. */ @Slf4j public class RangeShardManager extends ShardManager { @Override public int storeData(Data data) { var shardId = allocateShard(data); var shard = shardMap.get(shardId); shard.storeData(data); LOGGER.info(data.toString() + " is stored in Shard " + shardId); return shardId; } @Override protected int allocateShard(Data data) { var type = data.getType(); return switch (type) { case TYPE_1 -> 1; case TYPE_2 -> 2; case TYPE_3 -> 3; default -> -1; }; } }
2,021
34.473684
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/Data.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; /** * Basic data structure for each tuple stored in data shards. */ public class Data { private int key; private String value; private DataType type; /** * Constructor of Data class. * @param key data key * @param value data vlue * @param type data type */ public Data(final int key, final String value, final DataType type) { this.key = key; this.value = value; this.type = type; } public int getKey() { return key; } public void setKey(final int key) { this.key = key; } public String getValue() { return value; } public void setValue(final String value) { this.value = value; } public DataType getType() { return type; } public void setType(DataType type) { this.type = type; } enum DataType { TYPE_1, TYPE_2, TYPE_3 } @Override public String toString() { return "Data {" + "key=" + key + ", value='" + value + '\'' + ", type=" + type + '}'; } }
2,301
25.767442
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/ShardManager.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; /** * Abstract class for ShardManager. */ @Slf4j public abstract class ShardManager { protected Map<Integer, Shard> shardMap; public ShardManager() { shardMap = new HashMap<>(); } /** * Add a provided shard instance to shardMap. * * @param shard new shard instance. * @return {@code true} if succeed to add the new instance. * {@code false} if the shardId is already existed. */ public boolean addNewShard(final Shard shard) { var shardId = shard.getId(); if (!shardMap.containsKey(shardId)) { shardMap.put(shardId, shard); return true; } else { return false; } } /** * Remove a shard instance by provided Id. * * @param shardId Id of shard instance to remove. * @return {@code true} if removed. {@code false} if the shardId is not existed. */ public boolean removeShardById(final int shardId) { if (shardMap.containsKey(shardId)) { shardMap.remove(shardId); return true; } else { return false; } } /** * Get shard instance by provided shardId. * * @param shardId id of shard instance to get * @return required shard instance */ public Shard getShardById(final int shardId) { return shardMap.get(shardId); } /** * Store data in proper shard instance. * * @param data new data * @return id of shard that the data is stored in */ public abstract int storeData(final Data data); /** * Allocate proper shard to provided data. * * @param data new data * @return id of shard that the data should be stored */ protected abstract int allocateShard(final Data data); }
3,059
29
140
java
java-design-patterns
java-design-patterns-master/sharding/src/main/java/com/iluwatar/sharding/Shard.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.sharding; import java.util.HashMap; import java.util.Map; /** * The Shard class stored data in a HashMap. */ public class Shard { private final int id; private final Map<Integer, Data> dataStore; public Shard(final int id) { this.id = id; this.dataStore = new HashMap<>(); } public void storeData(Data data) { dataStore.put(data.getKey(), data); } public void clearData() { dataStore.clear(); } public Data getDataById(final int id) { return dataStore.get(id); } public int getId() { return id; } }
1,864
29.57377
140
java
java-design-patterns
java-design-patterns-master/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.event.queue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import javax.sound.sampled.UnsupportedAudioFileException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Testing the Audio service of the Queue * @author mkuprivecz * */ class AudioTest { private Audio audio; @BeforeEach void createAudioInstance() { audio = new Audio(); } /** * Test here that the playSound method works correctly * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @Test void testPlaySound() throws UnsupportedAudioFileException, IOException, InterruptedException { audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); // test that service is started assertTrue(audio.isServiceRunning()); // adding a small pause to be sure that the sound is ended Thread.sleep(5000); audio.stopService(); // test that service is finished assertFalse(audio.isServiceRunning()); } /** * Test here that the Queue * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable * @throws InterruptedException when the test is interrupted externally */ @Test void testQueue() throws UnsupportedAudioFileException, IOException, InterruptedException { audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); assertTrue(audio.getPendingAudio().length > 0); // test that service is started assertTrue(audio.isServiceRunning()); // adding a small pause to be sure that the sound is ended Thread.sleep(10000); audio.stopService(); // test that service is finished assertFalse(audio.isServiceRunning()); } }
3,444
36.445652
140
java
java-design-patterns
java-design-patterns-master/event-queue/src/main/java/com/iluwatar/event/queue/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.event.queue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.sound.sampled.UnsupportedAudioFileException; import lombok.extern.slf4j.Slf4j; /** * Event or message queues provide an asynchronous communications protocol, meaning that the sender * and receiver of the message do not need to interact with the message queue at the same time. * Events or messages placed onto the queue are stored until the recipient retrieves them. Event or * message queues have implicit or explicit limits on the size of data that may be transmitted in a * single message and the number of messages that may remain outstanding on the queue. A queue * stores a series of notifications or requests in first-in, first-out order. Sending a notification * enqueues the request and returns. The request processor then processes items from the queue at a * later time. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args * @throws IOException when there is a problem with the audio file loading * @throws UnsupportedAudioFileException when the loaded audio file is unsupported */ public static void main(String[] args) throws UnsupportedAudioFileException, IOException, InterruptedException { var audio = Audio.getInstance(); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); LOGGER.info("Press Enter key to stop the program..."); try (var br = new BufferedReader(new InputStreamReader(System.in))) { br.read(); } audio.stopService(); } }
3,006
44.560606
140
java
java-design-patterns
java-design-patterns-master/event-queue/src/main/java/com/iluwatar/event/queue/Audio.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.event.queue; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import lombok.extern.slf4j.Slf4j; /** * This class implements the Event Queue pattern. * * @author mkuprivecz */ @Slf4j public class Audio { private static final Audio INSTANCE = new Audio(); private static final int MAX_PENDING = 16; private int headIndex; private int tailIndex; private volatile Thread updateThread = null; private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; // Visible only for testing purposes Audio() { } public static Audio getInstance() { return INSTANCE; } /** * This method stops the Update Method's thread and waits till service stops. */ public synchronized void stopService() throws InterruptedException { if (updateThread != null) { updateThread.interrupt(); } updateThread.join(); updateThread = null; } /** * This method check the Update Method's thread is started. * * @return boolean */ public synchronized boolean isServiceRunning() { return updateThread != null && updateThread.isAlive(); } /** * Starts the thread for the Update Method pattern if it was not started previously. Also when the * thread is is ready initializes the indexes of the queue */ public void init() { if (updateThread == null) { updateThread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { update(); } }); } startThread(); } /** * This is a synchronized thread starter. */ private synchronized void startThread() { if (!updateThread.isAlive()) { updateThread.start(); headIndex = 0; tailIndex = 0; } } /** * This method adds a new audio into the queue. * * @param stream is the AudioInputStream for the method * @param volume is the level of the audio's volume */ public void playSound(AudioInputStream stream, float volume) { init(); // Walk the pending requests. for (var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) { var playMessage = getPendingAudio()[i]; if (playMessage.getStream() == stream) { // Use the larger of the two volumes. playMessage.setVolume(Math.max(volume, playMessage.getVolume())); // Don't need to enqueue. return; } } getPendingAudio()[tailIndex] = new PlayMessage(stream, volume); tailIndex = (tailIndex + 1) % MAX_PENDING; } /** * This method uses the Update Method pattern. It takes the audio from the queue and plays it */ private void update() { // If there are no pending requests, do nothing. if (headIndex == tailIndex) { return; } try { var audioStream = getPendingAudio()[headIndex].getStream(); headIndex++; var clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (LineUnavailableException e) { LOGGER.trace("Error occoured while loading the audio: The line is unavailable", e); } catch (IOException e) { LOGGER.trace("Input/Output error while loading the audio", e); } catch (IllegalArgumentException e) { LOGGER.trace("The system doesn't support the sound: " + e.getMessage(), e); } } /** * Returns the AudioInputStream of a file. * * @param filePath is the path of the audio file * @return AudioInputStream * @throws UnsupportedAudioFileException when the audio file is not supported * @throws IOException when the file is not readable */ public AudioInputStream getAudioStream(String filePath) throws UnsupportedAudioFileException, IOException { return AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile()); } /** * Returns with the message array of the queue. * * @return PlayMessage[] */ public PlayMessage[] getPendingAudio() { return pendingAudio; } }
5,446
29.601124
140
java
java-design-patterns
java-design-patterns-master/event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.event.queue; import javax.sound.sampled.AudioInputStream; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * The Event Queue's queue will store the instances of this class. * * @author mkuprivecz */ @Getter @AllArgsConstructor public class PlayMessage { private final AudioInputStream stream; @Setter private float volume; }
1,678
34.723404
140
java
java-design-patterns
java-design-patterns-master/twin/src/test/java/com/iluwatar/twin/BallItemTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * Date: 12/30/15 - 18:44 PM * * @author Jeroen Meulemeester */ class BallItemTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } @Test void testClick() { final var ballThread = mock(BallThread.class); final var ballItem = new BallItem(); ballItem.setTwin(ballThread); final var inOrder = inOrder(ballThread); IntStream.range(0, 10).forEach(i -> { ballItem.click(); inOrder.verify(ballThread).suspendMe(); ballItem.click(); inOrder.verify(ballThread).resumeMe(); }); inOrder.verifyNoMoreInteractions(); } @Test void testDoDraw() { final var ballItem = new BallItem(); final var ballThread = mock(BallThread.class); ballItem.setTwin(ballThread); ballItem.draw(); assertTrue(appender.logContains("draw")); assertTrue(appender.logContains("doDraw")); verifyNoMoreInteractions(ballThread); assertEquals(2, appender.getLogSize()); } @Test void testMove() { final var ballItem = new BallItem(); final var ballThread = mock(BallThread.class); ballItem.setTwin(ballThread); ballItem.move(); assertTrue(appender.logContains("move")); verifyNoMoreInteractions(ballThread); assertEquals(1, appender.getLogSize()); } /** * Logging Appender Implementation */ class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().anyMatch(event -> event.getMessage().equals(message)); } public int getLogSize() { return log.size(); } } }
3,928
28.320896
140
java
java-design-patterns
java-design-patterns-master/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import static java.lang.Thread.UncaughtExceptionHandler; import static java.lang.Thread.sleep; import static java.time.Duration.ofMillis; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; /** * Date: 12/30/15 - 18:55 PM * * @author Jeroen Meulemeester */ class BallThreadTest { /** * Verify if the {@link BallThread} can be resumed */ @Test void testSuspend() { assertTimeout(ofMillis(5000), () -> { final var ballThread = new BallThread(); final var ballItem = mock(BallItem.class); ballThread.setTwin(ballItem); ballThread.start(); sleep(200); verify(ballItem, atLeastOnce()).draw(); verify(ballItem, atLeastOnce()).move(); ballThread.suspendMe(); sleep(1000); ballThread.stopMe(); ballThread.join(); verifyNoMoreInteractions(ballItem); }); } /** * Verify if the {@link BallThread} can be resumed */ @Test void testResume() { assertTimeout(ofMillis(5000), () -> { final var ballThread = new BallThread(); final var ballItem = mock(BallItem.class); ballThread.setTwin(ballItem); ballThread.suspendMe(); ballThread.start(); sleep(1000); verifyNoMoreInteractions(ballItem); ballThread.resumeMe(); sleep(300); verify(ballItem, atLeastOnce()).draw(); verify(ballItem, atLeastOnce()).move(); ballThread.stopMe(); ballThread.join(); verifyNoMoreInteractions(ballItem); }); } /** * Verify if the {@link BallThread} is interruptible */ @Test void testInterrupt() { assertTimeout(ofMillis(5000), () -> { final var ballThread = new BallThread(); final var exceptionHandler = mock(UncaughtExceptionHandler.class); ballThread.setUncaughtExceptionHandler(exceptionHandler); ballThread.setTwin(mock(BallItem.class)); ballThread.start(); ballThread.interrupt(); ballThread.join(); verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); verifyNoMoreInteractions(exceptionHandler); }); } }
3,748
29.983471
140
java
java-design-patterns
java-design-patterns-master/twin/src/test/java/com/iluwatar/twin/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,572
37.365854
140
java
java-design-patterns
java-design-patterns-master/twin/src/main/java/com/iluwatar/twin/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; /** * Twin pattern is a design pattern which provides a standard solution to simulate multiple * inheritance in Java. * * <p>In this example, the essence of the Twin pattern is the {@link BallItem} class and {@link * BallThread} class represent the twin objects to coordinate with each other (via the twin * reference) like a single class inheriting from {@link GameItem} and {@link Thread}. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) throws Exception { var ballItem = new BallItem(); var ballThread = new BallThread(); ballItem.setTwin(ballThread); ballThread.setTwin(ballItem); ballThread.start(); waiting(); ballItem.click(); waiting(); ballItem.click(); waiting(); // exit ballThread.stopMe(); } private static void waiting() throws Exception { Thread.sleep(750); } }
2,259
30.830986
140
java
java-design-patterns
java-design-patterns-master/twin/src/main/java/com/iluwatar/twin/BallThread.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This class is a UI thread for drawing the {@link BallItem}, and provide the method for suspend * and resume. It hold the reference of {@link BallItem} to delegate the draw task. */ @Slf4j public class BallThread extends Thread { @Setter private BallItem twin; private volatile boolean isSuspended; private volatile boolean isRunning = true; /** * Run the thread. */ public void run() { while (isRunning) { if (!isSuspended) { twin.draw(); twin.move(); } try { Thread.sleep(250); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public void suspendMe() { isSuspended = true; LOGGER.info("Begin to suspend BallThread"); } public void resumeMe() { isSuspended = false; LOGGER.info("Begin to resume BallThread"); } public void stopMe() { this.isRunning = false; this.isSuspended = true; } }
2,324
28.43038
140
java
java-design-patterns
java-design-patterns-master/twin/src/main/java/com/iluwatar/twin/BallItem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This class represents a Ball which extends {@link GameItem} and implements the logic for ball * item, like move and draw. It hold a reference of {@link BallThread} to delegate the suspend and * resume task. */ @Slf4j public class BallItem extends GameItem { private boolean isSuspended; @Setter private BallThread twin; @Override public void doDraw() { LOGGER.info("doDraw"); } public void move() { LOGGER.info("move"); } @Override public void click() { isSuspended = !isSuspended; if (isSuspended) { twin.suspendMe(); } else { twin.resumeMe(); } } }
1,997
29.272727
140
java
java-design-patterns
java-design-patterns-master/twin/src/main/java/com/iluwatar/twin/GameItem.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.twin; import lombok.extern.slf4j.Slf4j; /** * GameItem is a common class which provides some common methods for game object. */ @Slf4j public abstract class GameItem { /** * Template method, do some common logic before draw. */ public void draw() { LOGGER.info("draw"); doDraw(); } public abstract void doDraw(); public abstract void click(); }
1,682
34.0625
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test case for creating and checking the Message. */ class MessageTest { @Test void messageTest() { // Parameterized constructor test. var testMsg = "Message Test"; var msg = new Message(testMsg); assertEquals(testMsg, msg.getMsg()); } }
1,694
36.666667
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test case for submitting Message to Blocking Queue by TaskGenerator and retrieve the message by * ServiceExecutor. */ class TaskGenSrvExeTest { @Test void taskGeneratorTest() { var msgQueue = new MessageQueue(); // Create a task generator thread with 1 job to submit. var taskRunnable = new TaskGenerator(msgQueue, 1); var taskGenThr = new Thread(taskRunnable); taskGenThr.start(); assertNotNull(taskGenThr); // Create a service executor thread. var srvRunnable = new ServiceExecutor(msgQueue); var srvExeThr = new Thread(srvRunnable); srvExeThr.start(); assertNotNull(srvExeThr); } }
2,135
35.827586
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test case for submitting and retrieving messages from Blocking Queue. */ class MessageQueueTest { @Test void messageQueueTest() { var msgQueue = new MessageQueue(); // submit message msgQueue.submitMsg(new Message("MessageQueue Test")); // retrieve message assertEquals("MessageQueue Test", msgQueue.retrieveMsg().getMsg()); } }
1,793
35.612245
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application Test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,597
38.95
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; /** * Many solutions in the cloud involve running tasks that invoke services. In this environment, if a * service is subjected to intermittent heavy loads, it can cause performance or reliability * issues. * * <p>A service could be a component that is part of the same solution as the tasks that utilize * it, or it could be a third-party service providing access to frequently used resources such as a * cache or a storage service. If the same service is utilized by a number of tasks running * concurrently, it can be difficult to predict the volume of requests to which the service might be * subjected at any given point in time. * * <p>We will build a queue-based-load-leveling to solve above problem. Refactor the solution and * introduce a queue between the task and the service. The task and the service run asynchronously. * The task posts a message containing the data required by the service to a queue. The queue acts * as a buffer, storing the message until it is retrieved by the service. The service retrieves the * messages from the queue and processes them. Requests from a number of tasks, which can be * generated at a highly variable rate, can be passed to the service through the same message * queue. * * <p>The queue effectively decouples the tasks from the service, and the service can handle the * messages at its own pace irrespective of the volume of requests from concurrent tasks. * Additionally, there is no delay to a task if the service is not available at the time it posts a * message to the queue. * * <p>In this example we have a class {@link MessageQueue} to hold the message {@link Message} * objects. All the worker threads {@link TaskGenerator} will submit the messages to the * MessageQueue. The service executor class {@link ServiceExecutor} will pick up one task at a time * from the Queue and execute them. */ @Slf4j public class App { //Executor shut down time limit. private static final int SHUTDOWN_TIME = 15; /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // An Executor that provides methods to manage termination and methods that can // produce a Future for tracking progress of one or more asynchronous tasks. ExecutorService executor = null; try { // Create a MessageQueue object. var msgQueue = new MessageQueue(); LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads."); // Create three TaskGenerator threads. Each of them will submit different number of jobs. final var taskRunnable1 = new TaskGenerator(msgQueue, 5); final var taskRunnable2 = new TaskGenerator(msgQueue, 1); final var taskRunnable3 = new TaskGenerator(msgQueue, 2); // Create e service which should process the submitted jobs. final var srvRunnable = new ServiceExecutor(msgQueue); // Create a ThreadPool of 2 threads and // submit all Runnable task for execution to executor.. executor = Executors.newFixedThreadPool(2); executor.submit(taskRunnable1); executor.submit(taskRunnable2); executor.submit(taskRunnable3); // submitting serviceExecutor thread to the Executor service. executor.submit(srvRunnable); // Initiates an orderly shutdown. LOGGER.info("Initiating shutdown." + " Executor will shutdown only after all the Threads are completed."); executor.shutdown(); // Wait for SHUTDOWN_TIME seconds for all the threads to complete // their tasks and then shut down the executor and then exit. if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) { LOGGER.info("Executor was shut down and Exiting."); executor.shutdownNow(); } } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
5,348
44.717949
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/ServiceExecutor.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import lombok.extern.slf4j.Slf4j; /** * ServiceExecuotr class. This class will pick up Messages one by one from the Blocking Queue and * process them. */ @Slf4j public class ServiceExecutor implements Runnable { private final MessageQueue msgQueue; public ServiceExecutor(MessageQueue msgQueue) { this.msgQueue = msgQueue; } /** * The ServiceExecutor thread will retrieve each message and process it. */ public void run() { try { while (!Thread.currentThread().isInterrupted()) { var msg = msgQueue.retrieveMsg(); if (null != msg) { LOGGER.info(msg.toString() + " is served."); } else { LOGGER.info("Service Executor: Waiting for Messages to serve .. "); } Thread.sleep(1000); } } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
2,186
34.274194
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/TaskGenerator.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import lombok.extern.slf4j.Slf4j; /** * TaskGenerator class. Each TaskGenerator thread will be a Worker which submit's messages to the * queue. We need to mention the message count for each of the TaskGenerator threads. */ @Slf4j public class TaskGenerator implements Task, Runnable { // MessageQueue reference using which we will submit our messages. private final MessageQueue msgQueue; // Total message count that a TaskGenerator will submit. private final int msgCount; // Parameterized constructor. public TaskGenerator(MessageQueue msgQueue, int msgCount) { this.msgQueue = msgQueue; this.msgCount = msgCount; } /** * Submit messages to the Blocking Queue. */ public void submit(Message msg) { try { this.msgQueue.submitMsg(msg); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * Each TaskGenerator thread will submit all the messages to the Queue. After every message * submission TaskGenerator thread will sleep for 1 second. */ public void run() { var count = this.msgCount; try { while (count > 0) { var statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName(); this.submit(new Message(statusMsg)); LOGGER.info(statusMsg); // reduce the message count. count--; // Make the current thread to sleep after every Message submission. Thread.sleep(1000); } } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
2,865
33.53012
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Message.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Message class with only one parameter. */ @Getter @RequiredArgsConstructor public class Message { private final String msg; @Override public String toString() { return msg; } }
1,586
36.785714
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/Task.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; /** * Task Interface. */ public interface Task { void submit(Message msg); }
1,408
41.69697
140
java
java-design-patterns
java-design-patterns-master/queue-load-leveling/src/main/java/com/iluwatar/queue/load/leveling/MessageQueue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.queue.load.leveling; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import lombok.extern.slf4j.Slf4j; /** * MessageQueue class. In this class we will create a Blocking Queue and submit/retrieve all the * messages from it. */ @Slf4j public class MessageQueue { private final BlockingQueue<Message> blkQueue; // Default constructor when called creates Blocking Queue object. public MessageQueue() { this.blkQueue = new ArrayBlockingQueue<>(1024); } /** * All the TaskGenerator threads will call this method to insert the Messages in to the Blocking * Queue. */ public void submitMsg(Message msg) { try { if (null != msg) { blkQueue.add(msg); } } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * All the messages will be retrieved by the ServiceExecutor by calling this method and process * them. Retrieves and removes the head of this queue, or returns null if this queue is empty. */ public Message retrieveMsg() { try { return blkQueue.poll(); } catch (Exception e) { LOGGER.error(e.getMessage()); } return null; } }
2,497
33.694444
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/SkyLaunchTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized; import static org.junit.jupiter.api.Assertions.assertEquals; import com.github.stefanbirkner.systemlambda.Statement; import org.junit.jupiter.api.Test; /** * SkyLaunch unit tests. */ class SkyLaunchTest { @Test void testMove() throws Exception { var skyLaunch = new SkyLaunch(); var outputLog = getLogContent(() -> skyLaunch.move(1.0, 1.0, 1.0)); var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; assertEquals(outputLog, expectedLog); } @Test void testPlaySound() throws Exception { var skyLaunch = new SkyLaunch(); var outputLog = getLogContent(() -> skyLaunch.playSound("SOUND_NAME", 1)); var expectedLog = "Play SOUND_NAME with volumn 1"; assertEquals(outputLog, expectedLog); } @Test void testSpawnParticles() throws Exception { var skyLaunch = new SkyLaunch(); var outputLog = getLogContent( () -> skyLaunch.spawnParticles("PARTICLE_TYPE", 100)); var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; assertEquals(outputLog, expectedLog); } @Test void testActivate() throws Exception { var skyLaunch = new SkyLaunch(); var logs = tapSystemOutNormalized(skyLaunch::activate) .split("\n"); final var expectedSize = 3; final var log1 = getLogContent(logs[0]); final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )"; final var log2 = getLogContent(logs[1]); final var expectedLog2 = "Play SKYLAUNCH_SOUND with volumn 1"; final var log3 = getLogContent(logs[2]); final var expectedLog3 = "Spawn 100 particle with type SKYLAUNCH_PARTICLE"; assertEquals(logs.length, expectedSize); assertEquals(log1, expectedLog1); assertEquals(log2, expectedLog2); assertEquals(log3, expectedLog3); } private String getLogContent(Statement statement) throws Exception { var log = tapSystemOutNormalized(statement); return getLogContent(log); } private String getLogContent(String log) { return log.split("-")[1].trim(); } }
3,395
36.733333
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * App unit tests. */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,582
37.609756
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/test/java/com/iluwatar/subclasssandbox/GroundDiveTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized; import static org.junit.jupiter.api.Assertions.assertEquals; import com.github.stefanbirkner.systemlambda.Statement; import org.junit.jupiter.api.Test; /** * GroundDive unit tests. */ class GroundDiveTest { @Test void testMove() throws Exception { var groundDive = new GroundDive(); groundDive.move(1.0, 1.0, 1.0); var outputLog = getLogContent(() -> groundDive.move(1.0, 1.0, 1.0)); var expectedLog = "Move to ( 1.0, 1.0, 1.0 )"; assertEquals(outputLog, expectedLog); } @Test void testPlaySound() throws Exception { var groundDive = new GroundDive(); var outputLog = getLogContent(() -> groundDive.playSound("SOUND_NAME", 1)); var expectedLog = "Play SOUND_NAME with volumn 1"; assertEquals(outputLog, expectedLog); } @Test void testSpawnParticles() throws Exception { var groundDive = new GroundDive(); final var outputLog = getLogContent( () -> groundDive.spawnParticles("PARTICLE_TYPE", 100)); final var expectedLog = "Spawn 100 particle with type PARTICLE_TYPE"; assertEquals(outputLog, expectedLog); } @Test void testActivate() throws Exception { var groundDive = new GroundDive(); var logs = tapSystemOutNormalized(groundDive::activate) .split("\n"); final var expectedSize = 3; final var log1 = logs[0].split("-")[1].trim() + " -" + logs[0].split("-")[2].trim(); final var expectedLog1 = "Move to ( 0.0, 0.0, -20.0 )"; final var log2 = getLogContent(logs[1]); final var expectedLog2 = "Play GROUNDDIVE_SOUND with volumn 5"; final var log3 = getLogContent(logs[2]); final var expectedLog3 = "Spawn 20 particle with type GROUNDDIVE_PARTICLE"; assertEquals(logs.length, expectedSize); assertEquals(log1, expectedLog1); assertEquals(log2, expectedLog2); assertEquals(log3, expectedLog3); } private String getLogContent(Statement statement) throws Exception { var log = tapSystemOutNormalized(statement); return getLogContent(log); } private String getLogContent(String log) { return log.split("-")[1].trim(); } }
3,504
37.097826
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import lombok.extern.slf4j.Slf4j; /** * The subclass sandbox pattern describes a basic idea, while not having a lot * of detailed mechanics. You will need the pattern when you have several similar * subclasses. If you have to make a tiny change, then change the base class, * while all subclasses shouldn't have to be touched. So the base class has to be * able to provide all of the operations a derived class needs to perform. */ @Slf4j public class App { /** * Entry point of the main program. * @param args Program runtime arguments. */ public static void main(String[] args) { LOGGER.info("Use superpower: sky launch"); var skyLaunch = new SkyLaunch(); skyLaunch.activate(); LOGGER.info("Use superpower: ground dive"); var groundDive = new GroundDive(); groundDive.activate(); } }
2,157
39.716981
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/GroundDive.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import org.slf4j.LoggerFactory; /** * GroundDive superpower. */ public class GroundDive extends Superpower { public GroundDive() { super(); logger = LoggerFactory.getLogger(GroundDive.class); } @Override protected void activate() { move(0, 0, -20); playSound("GROUNDDIVE_SOUND", 5); spawnParticles("GROUNDDIVE_PARTICLE", 20); } }
1,688
35.717391
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import org.slf4j.Logger; /** * Superpower abstract class. In this class the basic operations of all types of * superpowers are provided as protected methods. */ public abstract class Superpower { protected Logger logger; /** * Subclass of superpower should implement this sandbox method by calling the * methods provided in this super class. */ protected abstract void activate(); /** * Move to (x, y, z). * @param x X coordinate. * @param y Y coordinate. * @param z Z coordinate. */ protected void move(double x, double y, double z) { logger.info("Move to ( " + x + ", " + y + ", " + z + " )"); } /** * Play sound effect for the superpower. * @param soundName Sound name. * @param volumn Value of volumn. */ protected void playSound(String soundName, int volumn) { logger.info("Play " + soundName + " with volumn " + volumn); } /** * Spawn particles for the superpower. * @param particleType Particle type. * @param count Count of particles to be spawned. */ protected void spawnParticles(String particleType, int count) { logger.info("Spawn " + count + " particle with type " + particleType); } }
2,515
34.43662
140
java
java-design-patterns
java-design-patterns-master/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/SkyLaunch.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.subclasssandbox; import org.slf4j.LoggerFactory; /** * SkyLaunch superpower. */ public class SkyLaunch extends Superpower { public SkyLaunch() { super(); logger = LoggerFactory.getLogger(SkyLaunch.class); } @Override protected void activate() { move(0, 0, 20); playSound("SKYLAUNCH_SOUND", 1); spawnParticles("SKYLAUNCH_PARTICLE", 100); } }
1,682
35.586957
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/test/java/com/iluwatar/compositeentity/PersistenceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PersistenceTest { final static ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); @Test void dependentObjectChangedForPersistenceTest() { MessageDependentObject dependentObject = new MessageDependentObject(); console.init(); console.dependentObjects[0] = dependentObject; String message = "Danger"; assertNull(console.dependentObjects[0].getData()); dependentObject.setData(message); assertEquals(message, console.dependentObjects[0].getData()); } @Test void coarseGrainedObjectChangedForPersistenceTest() { MessageDependentObject dependentObject = new MessageDependentObject(); console.init(); console.dependentObjects[0] = dependentObject; String message = "Danger"; assertNull(console.dependentObjects[0].getData()); console.setData(message); assertEquals(message, dependentObject.getData()); } }
2,309
39.526316
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/test/java/com/iluwatar/compositeentity/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; /** * com.iluwatar.compositeentity.App running test */ class AppTest { /** * Issue: Add at least one assertion to this test case. * <p> * Solution: Inserted assertion to check whether the execution of the main method in {@link * App#main(String[])} throws an exception. */ @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,845
35.92
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** * Composite entity is a Java EE Software design pattern and it is used to model, represent, and * manage a set of interrelated persistent objects rather than representing them as individual * fine-grained entity beans, and also a composite entity bean represents a graph of objects. */ @Slf4j public class App { /** * An instance that a console manages two related objects. */ public App(String message, String signal) { var console = new CompositeEntity(); console.init(); console.setData(message, signal); Arrays.stream(console.getData()).forEach(LOGGER::info); console.setData("Danger", "Red Light"); Arrays.stream(console.getData()).forEach(LOGGER::info); } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { new App("No Danger", "Green Light"); } }
2,263
34.936508
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/DependentObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; /** * It is an object, which can contain other dependent objects (there may be a tree of objects within * the composite entity), that depends on the coarse-grained object and has its life cycle managed * by the coarse-grained object. */ public abstract class DependentObject<T> { T data; public void setData(T message) { this.data = message; } public T getData() { return data; } }
1,731
37.488889
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/MessageDependentObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; /** * The first DependentObject to show message. */ public class MessageDependentObject extends DependentObject<String> { }
1,450
42.969697
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/ConsoleCoarseGrainedObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; /** * A specific CoarseGrainedObject to implement a console. */ public class ConsoleCoarseGrainedObject extends CoarseGrainedObject<String> { @Override public String[] getData() { return new String[]{ dependentObjects[0].getData(), dependentObjects[1].getData() }; } public void init() { dependentObjects = new DependentObject[]{ new MessageDependentObject(), new SignalDependentObject()}; } }
1,759
39
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/SignalDependentObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; /** * The second DependentObject to show message. */ public class SignalDependentObject extends DependentObject<String> { }
1,450
42.969697
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/CompositeEntity.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; /** * Composite entity is the coarse-grained entity bean which may be the coarse-grained object, or may * contain a reference to the coarse-grained object. */ public class CompositeEntity { private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject(); public void setData(String message, String signal) { console.setData(message, signal); } public String[] getData() { return console.getData(); } public void init() { console.init(); } }
1,817
37.680851
140
java
java-design-patterns
java-design-patterns-master/composite-entity/src/main/java/com/iluwatar/compositeentity/CoarseGrainedObject.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.compositeentity; import java.util.Arrays; import java.util.stream.IntStream; /** * A coarse-grained object is an object with its own life cycle manages its own relationships to * other objects. It can be an object contained in the composite entity, or, composite entity itself * can be the coarse-grained object which holds dependent objects. */ public abstract class CoarseGrainedObject<T> { DependentObject<T>[] dependentObjects; public void setData(T... data) { IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i])); } public T[] getData() { return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray(); } }
1,997
40.625
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/OldArithmeticTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test methods in OldArithmetic */ class OldArithmeticTest { private static final OldArithmetic arithmetic = new OldArithmetic(new OldSource()); @Test void testSum() { assertEquals(0, arithmetic.sum(-1, 0, 1)); } @Test void testMul() { assertEquals(0, arithmetic.mul(-1, 0, 1)); } }
1,727
36.565217
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/HalfSourceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * Test methods in HalfSource */ class HalfSourceTest { private static final HalfSource source = new HalfSource(); @Test void testAccumulateSum() { assertEquals(0, source.accumulateSum(-1, 0, 1)); } @Test void testIfNonZero() { assertFalse(source.ifNonZero(-1, 0, 1)); } }
1,777
36.041667
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/HalfArithmeticTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Test methods in HalfArithmetic */ class HalfArithmeticTest { private static final HalfArithmetic arithmetic = new HalfArithmetic(new HalfSource(), new OldSource()); @Test void testSum() { assertEquals(0, arithmetic.sum(-1, 0, 1)); } @Test void testMul() { assertEquals(0, arithmetic.mul(-1, 0, 1)); } @Test void testIfHasZero() { assertTrue(arithmetic.ifHasZero(-1, 0, 1)); } }
1,894
35.442308
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/NewArithmeticTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * Test methods in NewArithmetic */ class NewArithmeticTest { private static final NewArithmetic arithmetic = new NewArithmetic(new NewSource()); @Test void testSum() { assertEquals(0, arithmetic.sum(-1, 0, 1)); } @Test void testMul() { assertEquals(0, arithmetic.mul(-1, 0, 1)); } @Test void testIfHasZero() { assertTrue(arithmetic.ifHasZero(-1, 0, 1)); } }
1,872
35.019231
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/NewSourceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; /** * Test methods in NewSource */ class NewSourceTest { private static final NewSource source = new NewSource(); @Test void testAccumulateSum() { assertEquals(0, source.accumulateSum(-1, 0, 1)); } @Test void testAccumulateMul() { assertEquals(0, source.accumulateMul(-1, 0, 1)); } @Test void testIfNonZero() { assertFalse(source.ifNonZero(-1, 0, 1)); } }
1,868
34.264151
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/OldSourceTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test methods in OldSource */ class OldSourceTest { private static final OldSource source = new OldSource(); @Test void testAccumulateSum() { assertEquals(0, source.accumulateSum(-1, 0, 1)); } @Test void testAccumulateMul() { assertEquals(0, source.accumulateMul(-1, 0, 1)); } }
1,725
35.723404
140
java
java-design-patterns
java-design-patterns-master/strangler/src/test/java/com/iluwatar/strangler/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,577
37.487805
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; /** * * <p>The Strangler pattern is a software design pattern that incrementally migrate a legacy * system by gradually replacing specific pieces of functionality with new applications and * services. As features from the legacy system are replaced, the new system eventually * replaces all of the old system's features, strangling the old system and allowing you * to decommission it.</p> * * <p>This pattern is not only about updating but also enhancement.</p> * * <p>In this example, {@link OldArithmetic} indicates old system and its implementation depends * on its source ({@link OldSource}). Now we tend to update system with new techniques and * new features. In reality, the system may too complex, so usually need gradual migration. * {@link HalfArithmetic} indicates system in the process of migration, its implementation * depends on old one ({@link OldSource}) and under development one ({@link HalfSource}). The * {@link HalfSource} covers part of {@link OldSource} and add new functionality. You can release * this version system with new features, which also supports old version system functionalities. * After whole migration, the new system ({@link NewArithmetic}) only depends on new source * ({@link NewSource}).</p> * */ public class App { /** * Program entry point. * @param args command line args */ public static void main(final String[] args) { final var nums = new int[]{1, 2, 3, 4, 5}; //Before migration final var oldSystem = new OldArithmetic(new OldSource()); oldSystem.sum(nums); oldSystem.mul(nums); //In process of migration final var halfSystem = new HalfArithmetic(new HalfSource(), new OldSource()); halfSystem.sum(nums); halfSystem.mul(nums); halfSystem.ifHasZero(nums); //After migration final var newSystem = new NewArithmetic(new NewSource()); newSystem.sum(nums); newSystem.mul(nums); newSystem.ifHasZero(nums); } }
3,269
45.056338
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import lombok.extern.slf4j.Slf4j; /** * Old version system depends on old version source ({@link OldSource}). */ @Slf4j public class OldArithmetic { private static final String VERSION = "1.0"; private final OldSource source; public OldArithmetic(OldSource source) { this.source = source; } /** * Accumulate sum. * @param nums numbers need to add together * @return accumulate sum */ public int sum(int... nums) { LOGGER.info("Arithmetic sum {}", VERSION); return source.accumulateSum(nums); } /** * Accumulate multiplication. * @param nums numbers need to multiply together * @return accumulate multiplication */ public int mul(int... nums) { LOGGER.info("Arithmetic mul {}", VERSION); return source.accumulateMul(nums); } }
2,114
33.112903
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/OldSource.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import lombok.extern.slf4j.Slf4j; /** * Old source with techniques out of date. */ @Slf4j public class OldSource { private static final String VERSION = "1.0"; /** * Implement accumulate sum with old technique. */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 0; for (final var num : nums) { sum += num; } return sum; } /** * Implement accumulate multiply with old technique. */ public int accumulateMul(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 1; for (final var num : nums) { sum *= num; } return sum; } }
1,979
32
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/NewArithmetic.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import lombok.extern.slf4j.Slf4j; /** * System after whole migration. Only depends on new version source ({@link NewSource}). */ @Slf4j public class NewArithmetic { private static final String VERSION = "2.0"; private final NewSource source; public NewArithmetic(NewSource source) { this.source = source; } /** * Accumulate sum. * @param nums numbers need to add together * @return accumulate sum */ public int sum(int... nums) { LOGGER.info("Arithmetic sum {}", VERSION); return source.accumulateSum(nums); } /** * Accumulate multiplication. * @param nums numbers need to multiply together * @return accumulate multiplication */ public int mul(int... nums) { LOGGER.info("Arithmetic mul {}", VERSION); return source.accumulateMul(nums); } /** * Chech if has any zero. * @param nums numbers need to check * @return if has any zero, return true, else, return false */ public boolean ifHasZero(int... nums) { LOGGER.info("Arithmetic check zero {}", VERSION); return !source.ifNonZero(nums); } }
2,408
32.458333
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** * Source under development. Replace part of old source and has added some new features. */ @Slf4j public class HalfSource { private static final String VERSION = "1.5"; /** * Implement accumulate sum with new technique. * Replace old one in {@link OldSource} */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).reduce(0, Integer::sum); } /** * Check if all number is not zero. * New feature. */ public boolean ifNonZero(int... nums) { LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).allMatch(num -> num != 0); } }
2,028
35.890909
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/HalfArithmetic.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import lombok.extern.slf4j.Slf4j; /** * System under migration. Depends on old version source ({@link OldSource}) and * developing one ({@link HalfSource}). */ @Slf4j public class HalfArithmetic { private static final String VERSION = "1.5"; private final HalfSource newSource; private final OldSource oldSource; public HalfArithmetic(HalfSource newSource, OldSource oldSource) { this.newSource = newSource; this.oldSource = oldSource; } /** * Accumulate sum. * @param nums numbers need to add together * @return accumulate sum */ public int sum(int... nums) { LOGGER.info("Arithmetic sum {}", VERSION); return newSource.accumulateSum(nums); } /** * Accumulate multiplication. * @param nums numbers need to multiply together * @return accumulate multiplication */ public int mul(int... nums) { LOGGER.info("Arithmetic mul {}", VERSION); return oldSource.accumulateMul(nums); } /** * Chech if has any zero. * @param nums numbers need to check * @return if has any zero, return true, else, return false */ public boolean ifHasZero(int... nums) { LOGGER.info("Arithmetic check zero {}", VERSION); return !newSource.ifNonZero(nums); } }
2,555
33.08
140
java
java-design-patterns
java-design-patterns-master/strangler/src/main/java/com/iluwatar/strangler/NewSource.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.strangler; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; /** * New source. Completely covers functionalities of old source with new techniques * and also has some new features. */ @Slf4j public class NewSource { private static final String VERSION = "2.0"; public static final String SOURCE_MODULE = "Source module {}"; public int accumulateSum(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).reduce(0, Integer::sum); } /** * Implement accumulate multiply with new technique. * Replace old one in {@link OldSource} */ public int accumulateMul(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).reduce(1, (a, b) -> a * b); } public boolean ifNonZero(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).allMatch(num -> num != 0); } }
2,195
36.862069
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.privateclassdata.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 10:46 PM * * @author Jeroen Meulemeester */ class ImmutableStewTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * Verify if mixing the stew doesn't change the internal state */ @Test void testMix() { var stew = new Stew(1, 2, 3, 4); var expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; for (var i = 0; i < 20; i++) { stew.mix(); assertEquals(expectedMessage, appender.getLastMessage()); } assertEquals(20, appender.getLogSize()); } /** * Verify if tasting the stew actually removes one of each ingredient */ @Test void testDrink() { final var stew = new Stew(1, 2, 3, 4); stew.mix(); assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender .getLastMessage()); stew.taste(); assertEquals("Tasting the stew", appender.getLastMessage()); stew.mix(); assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender .getLastMessage()); } }
2,780
30.602273
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; import static org.junit.jupiter.api.Assertions.assertEquals; import com.iluwatar.privateclassdata.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 10:46 PM * * @author Jeroen Meulemeester */ class StewTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * Verify if mixing the stew doesn't change the internal state */ @Test void testMix() { final var stew = new ImmutableStew(1, 2, 3, 4); final var expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + "2 carrots, 3 meat and 4 peppers"; for (var i = 0; i < 20; i++) { stew.mix(); assertEquals(expectedMessage, appender.getLastMessage()); } assertEquals(20, appender.getLogSize()); } }
2,285
31.197183
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,595
37.926829
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/test/java/com/iluwatar/privateclassdata/utils/InMemoryAppender.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; /** * InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public int getLogSize() { return log.size(); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } }
2,078
34.844828
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/main/java/com/iluwatar/privateclassdata/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; /** * The Private Class Data design pattern seeks to reduce exposure of attributes by limiting their * visibility. It reduces the number of class attributes by encapsulating them in single data * object. It allows the class designer to remove write privilege of attributes that are intended to * be set only during construction, even from methods of the target class. * * <p>In the example we have normal {@link Stew} class with some ingredients given in constructor. * Then we have methods to enumerate the ingredients and to taste the stew. The method for tasting * the stew alters the private members of the {@link Stew} class. * * <p>The problem is solved with the Private Class Data pattern. We introduce {@link ImmutableStew} * class that contains {@link StewData}. The private data members of {@link Stew} are now in {@link * StewData} and cannot be altered by {@link ImmutableStew} methods. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // stew is mutable var stew = new Stew(1, 2, 3, 4); stew.mix(); stew.taste(); stew.mix(); // immutable stew protected with Private Class Data pattern var immutableStew = new ImmutableStew(2, 4, 3, 6); immutableStew.mix(); } }
2,641
43.033333
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/main/java/com/iluwatar/privateclassdata/StewData.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; /** * Stew ingredients. */ public record StewData(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { }
1,443
42.757576
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/main/java/com/iluwatar/privateclassdata/ImmutableStew.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; import lombok.extern.slf4j.Slf4j; /** * Immutable stew class, protected with Private Class Data pattern. */ @Slf4j public class ImmutableStew { private final StewData data; public ImmutableStew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { data = new StewData(numPotatoes, numCarrots, numMeat, numPeppers); } /** * Mix the stew. */ public void mix() { LOGGER .info("Mixing the immutable stew we find: {} potatoes, {} carrots, {} meat and {} peppers", data.numPotatoes(), data.numCarrots(), data.numMeat(), data.numPeppers()); } }
1,924
37.5
140
java
java-design-patterns
java-design-patterns-master/private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.privateclassdata; import lombok.extern.slf4j.Slf4j; /** * Mutable stew class. */ @Slf4j public class Stew { private int numPotatoes; private int numCarrots; private int numMeat; private int numPeppers; /** * Constructor. */ public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) { this.numPotatoes = numPotatoes; this.numCarrots = numCarrots; this.numMeat = numMeat; this.numPeppers = numPeppers; } /** * Mix the stew. */ public void mix() { LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers", numPotatoes, numCarrots, numMeat, numPeppers); } /** * Taste the stew. */ public void taste() { LOGGER.info("Tasting the stew"); if (numPotatoes > 0) { numPotatoes--; } if (numCarrots > 0) { numCarrots--; } if (numMeat > 0) { numMeat--; } if (numPeppers > 0) { numPeppers--; } } }
2,275
28.558442
140
java
java-design-patterns
java-design-patterns-master/property/src/test/java/com/iluwatar/property/CharacterTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; import static com.iluwatar.property.Character.Type; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import org.junit.jupiter.api.Test; /** * Date: 12/28/15 - 7:46 PM * * @author Jeroen Meulemeester */ class CharacterTest { @Test void testPrototypeStats() throws Exception { final var prototype = new Character(); for (final var stat : Stats.values()) { assertFalse(prototype.has(stat)); assertNull(prototype.get(stat)); final var expectedValue = stat.ordinal(); prototype.set(stat, expectedValue); assertTrue(prototype.has(stat)); assertEquals(expectedValue, prototype.get(stat)); prototype.remove(stat); assertFalse(prototype.has(stat)); assertNull(prototype.get(stat)); } } @Test void testCharacterStats() { final var prototype = new Character(); Arrays.stream(Stats.values()).forEach(stat -> prototype.set(stat, stat.ordinal())); final var mage = new Character(Type.MAGE, prototype); for (final var stat : Stats.values()) { final var expectedValue = stat.ordinal(); assertTrue(mage.has(stat)); assertEquals(expectedValue, mage.get(stat)); } } @Test void testToString() { final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.AGILITY, 2); prototype.set(Stats.INTELLECT, 3); assertEquals("Stats:\n - AGILITY:2\n - ARMOR:1\n - INTELLECT:3\n", prototype.toString()); final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertEquals("Character type: ROGUE\nStats:\n - AGILITY:2\n - ARMOR:1\n", stupid.toString()); final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertEquals("Player: weak\nStats:\n - AGILITY:2\n - INTELLECT:3\n", weak.toString()); } @Test void testName() { final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.name()); final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertNull(stupid.name()); final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertEquals("weak", weak.name()); } @Test void testType() { final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.type()); final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertEquals(Type.ROGUE, stupid.type()); final var weak = new Character("weak", prototype); weak.remove(Stats.ARMOR); assertNull(weak.type()); } }
4,248
32.722222
140
java
java-design-patterns
java-design-patterns-master/property/src/test/java/com/iluwatar/property/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,576
37.463415
140
java
java-design-patterns
java-design-patterns-master/property/src/main/java/com/iluwatar/property/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; import com.iluwatar.property.Character.Type; import lombok.extern.slf4j.Slf4j; /** * The Property pattern is also known as Prototype inheritance. * * <p>In prototype inheritance instead of classes, as opposite to Java class inheritance, objects * are used to create another objects and object hierarchies. Hierarchies are created using * prototype chain through delegation: every object has link to parent object. Any base (parent) * object can be amended at runtime (by adding or removal of some property), and all child objects * will be affected as result. * * <p>In this example we demonstrate {@link Character} instantiation using the Property pattern. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { /* set up */ var charProto = new Character(); charProto.set(Stats.STRENGTH, 10); charProto.set(Stats.AGILITY, 10); charProto.set(Stats.ARMOR, 10); charProto.set(Stats.ATTACK_POWER, 10); var mageProto = new Character(Type.MAGE, charProto); mageProto.set(Stats.INTELLECT, 15); mageProto.set(Stats.SPIRIT, 10); var warProto = new Character(Type.WARRIOR, charProto); warProto.set(Stats.RAGE, 15); warProto.set(Stats.ARMOR, 15); // boost default armor for warrior var rogueProto = new Character(Type.ROGUE, charProto); rogueProto.set(Stats.ENERGY, 15); rogueProto.set(Stats.AGILITY, 15); // boost default agility for rogue /* usage */ var mag = new Character("Player_1", mageProto); mag.set(Stats.ARMOR, 8); LOGGER.info(mag.toString()); var warrior = new Character("Player_2", warProto); LOGGER.info(warrior.toString()); var rogue = new Character("Player_3", rogueProto); LOGGER.info(rogue.toString()); var rogueDouble = new Character("Player_4", rogue); rogueDouble.set(Stats.ATTACK_POWER, 12); LOGGER.info(rogueDouble.toString()); } }
3,281
37.611765
140
java
java-design-patterns
java-design-patterns-master/property/src/main/java/com/iluwatar/property/Prototype.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; /** * Interface for prototype inheritance. */ public interface Prototype { Integer get(Stats stat); boolean has(Stats stat); void set(Stats stat, Integer val); void remove(Stats stat); }
1,517
36.95
140
java
java-design-patterns
java-design-patterns-master/property/src/main/java/com/iluwatar/property/Character.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; import java.util.HashMap; import java.util.Map; /** * Represents Character in game and his abilities (base stats). */ public class Character implements Prototype { /** * Enumeration of Character types. */ public enum Type { WARRIOR, MAGE, ROGUE } private final Prototype prototype; private final Map<Stats, Integer> properties = new HashMap<>(); private String name; private Type type; /** * Constructor. */ public Character() { this.prototype = new Prototype() { // Null-value object @Override public Integer get(Stats stat) { return null; } @Override public boolean has(Stats stat) { return false; } @Override public void set(Stats stat, Integer val) { // Does Nothing } @Override public void remove(Stats stat) { // Does Nothing. } }; } public Character(Type type, Prototype prototype) { this.type = type; this.prototype = prototype; } /** * Constructor. */ public Character(String name, Character prototype) { this.name = name; this.type = prototype.type; this.prototype = prototype; } public String name() { return name; } public Type type() { return type; } @Override public Integer get(Stats stat) { var containsValue = properties.containsKey(stat); if (containsValue) { return properties.get(stat); } else { return prototype.get(stat); } } @Override public boolean has(Stats stat) { return get(stat) != null; } @Override public void set(Stats stat, Integer val) { properties.put(stat, val); } @Override public void remove(Stats stat) { properties.put(stat, null); } @Override public String toString() { var builder = new StringBuilder(); if (name != null) { builder.append("Player: ").append(name).append('\n'); } if (type != null) { builder.append("Character type: ").append(type.name()).append('\n'); } builder.append("Stats:\n"); for (var stat : Stats.values()) { var value = this.get(stat); if (value == null) { continue; } builder.append(" - ").append(stat.name()).append(':').append(value).append('\n'); } return builder.toString(); } }
3,639
24.103448
140
java
java-design-patterns
java-design-patterns-master/property/src/main/java/com/iluwatar/property/Stats.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.property; /** * All possible attributes that Character can have. */ public enum Stats { AGILITY, STRENGTH, ATTACK_POWER, ARMOR, INTELLECT, SPIRIT, ENERGY, RAGE }
1,473
42.352941
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.HashSet; import org.junit.jupiter.api.Test; /** * Date: 12/12/15 - 10:54 PM * * @author Jeroen Meulemeester */ class AlchemistShopTest { @Test void testShop() { final var shop = new AlchemistShop(); final var bottomShelf = shop.getBottomShelf(); assertNotNull(bottomShelf); assertEquals(5, bottomShelf.size()); final var topShelf = shop.getTopShelf(); assertNotNull(topShelf); assertEquals(8, topShelf.size()); final var allPotions = new ArrayList<Potion>(); allPotions.addAll(topShelf); allPotions.addAll(bottomShelf); // There are 13 potion instances, but only 5 unique instance types assertEquals(13, allPotions.size()); assertEquals(5, new HashSet<>(allPotions).size()); } }
2,233
35.032258
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,588
37.756098
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; /** * Flyweight pattern is useful when the program needs a huge amount of objects. It provides means to * decrease resource usage by sharing object instances. * * <p>In this example {@link AlchemistShop} has great amount of potions on its shelves. To fill the * shelves {@link AlchemistShop} uses {@link PotionFactory} (which represents the Flyweight in this * example). Internally {@link PotionFactory} holds a map of the potions and lazily creates new ones * when requested. * * <p>To enable safe sharing, between clients and threads, Flyweight objects must be immutable. * Flyweight objects are by definition value objects. */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { // create the alchemist shop with the potions var alchemistShop = new AlchemistShop(); // a brave visitor enters the alchemist shop and drinks all the potions alchemistShop.drinkPotions(); } }
2,310
42.603774
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/InvisibilityPotion.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import lombok.extern.slf4j.Slf4j; /** * InvisibilityPotion. */ @Slf4j public class InvisibilityPotion implements Potion { @Override public void drink() { LOGGER.info("You become invisible. (Potion={})", System.identityHashCode(this)); } }
1,570
38.275
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/Potion.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; /** * Interface for Potions. */ public interface Potion { void drink(); }
1,396
40.088235
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/PotionFactory.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import java.util.EnumMap; import java.util.Map; /** * PotionFactory is the Flyweight in this example. It minimizes memory use by sharing object * instances. It holds a map of potion instances and new potions are created only when none of the * type already exists. */ public class PotionFactory { private final Map<PotionType, Potion> potions; public PotionFactory() { potions = new EnumMap<>(PotionType.class); } Potion createPotion(PotionType type) { var potion = potions.get(type); if (potion == null) { switch (type) { case HEALING -> potion = new HealingPotion(); case HOLY_WATER -> potion = new HolyWaterPotion(); case INVISIBILITY -> potion = new InvisibilityPotion(); case POISON -> potion = new PoisonPotion(); case STRENGTH -> potion = new StrengthPotion(); default -> { } } if (potion != null) { potions.put(type, potion); } } return potion; } }
2,300
36.112903
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import lombok.extern.slf4j.Slf4j; /** * HealingPotion. */ @Slf4j public class HealingPotion implements Potion { @Override public void drink() { LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this)); } }
1,555
37.9
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import lombok.extern.slf4j.Slf4j; /** * StrengthPotion. */ @Slf4j public class StrengthPotion implements Potion { @Override public void drink() { LOGGER.info("You feel strong. (Potion={})", System.identityHashCode(this)); } }
1,557
37.95
140
java
java-design-patterns
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/HolyWaterPotion.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 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.flyweight; import lombok.extern.slf4j.Slf4j; /** * HolyWaterPotion. */ @Slf4j public class HolyWaterPotion implements Potion { @Override public void drink() { LOGGER.info("You feel blessed. (Potion={})", System.identityHashCode(this)); } }
1,560
38.025
140
java