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/flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.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;
/**
* PoisonPotion.
*/
@Slf4j
public class PoisonPotion implements Potion {
@Override
public void drink() {
LOGGER.info("Urgh! This is poisonous. (Potion={})", System.identityHashCode(this));
}
}
| 1,561
| 38.05
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/PotionType.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;
/**
* Enumeration for potion types.
*/
public enum PotionType {
HEALING, INVISIBILITY, STRENGTH, HOLY_WATER, POISON
}
| 1,440
| 41.382353
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.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.List;
import lombok.extern.slf4j.Slf4j;
/**
* AlchemistShop holds potions on its shelves. It uses PotionFactory to provide the potions.
*/
@Slf4j
public class AlchemistShop {
private final List<Potion> topShelf;
private final List<Potion> bottomShelf;
/**
* Constructor.
*/
public AlchemistShop() {
var factory = new PotionFactory();
topShelf = List.of(
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.STRENGTH),
factory.createPotion(PotionType.HEALING),
factory.createPotion(PotionType.INVISIBILITY),
factory.createPotion(PotionType.STRENGTH),
factory.createPotion(PotionType.HEALING),
factory.createPotion(PotionType.HEALING)
);
bottomShelf = List.of(
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.POISON),
factory.createPotion(PotionType.HOLY_WATER),
factory.createPotion(PotionType.HOLY_WATER)
);
}
/**
* Get a read-only list of all the items on the top shelf.
*
* @return The top shelf potions
*/
public final List<Potion> getTopShelf() {
return List.copyOf(this.topShelf);
}
/**
* Get a read-only list of all the items on the bottom shelf.
*
* @return The bottom shelf potions
*/
public final List<Potion> getBottomShelf() {
return List.copyOf(this.bottomShelf);
}
/**
* Drink all the potions.
*/
public void drinkPotions() {
LOGGER.info("Drinking top shelf potions");
topShelf.forEach(Potion::drink);
LOGGER.info("Drinking bottom shelf potions");
bottomShelf.forEach(Potion::drink);
}
}
| 3,094
| 33.010989
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.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.strategy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.jupiter.api.Test;
/**
* Date: 12/29/15 - 10:50 PM.
*
* @author Jeroen Meulemeester
*/
class DragonSlayerTest {
/**
* Verify if the dragon slayer uses the strategy during battle.
*/
@Test
void testGoToBattle() {
final var strategy = mock(DragonSlayingStrategy.class);
final var dragonSlayer = new DragonSlayer(strategy);
dragonSlayer.goToBattle();
verify(strategy).execute();
verifyNoMoreInteractions(strategy);
}
/**
* Verify if the dragon slayer uses the new strategy during battle after a change of strategy.
*/
@Test
void testChangeStrategy() {
final var initialStrategy = mock(DragonSlayingStrategy.class);
final var dragonSlayer = new DragonSlayer(initialStrategy);
dragonSlayer.goToBattle();
verify(initialStrategy).execute();
final var newStrategy = mock(DragonSlayingStrategy.class);
dragonSlayer.changeStrategy(newStrategy);
dragonSlayer.goToBattle();
verify(newStrategy).execute();
verifyNoMoreInteractions(initialStrategy, newStrategy);
}
}
| 2,523
| 34.055556
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.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.strategy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
/**
* Date: 12/29/15 - 10:58 PM.
*
* @author Jeroen Meulemeester
*/
class DragonSlayingStrategyTest {
/**
* Assembles test parameters.
*
* @return The test parameters for each cycle
*/
static Collection<Object[]> dataProvider() {
return List.of(
new Object[]{
new MeleeStrategy(),
"With your Excalibur you sever the dragon's head!"
},
new Object[]{
new ProjectileStrategy(),
"You shoot the dragon with the magical crossbow and it falls dead on the ground!"
},
new Object[]{
new SpellStrategy(),
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"
}
);
}
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender();
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test if executing the strategy gives the correct response.
*/
@ParameterizedTest
@MethodSource("dataProvider")
void testExecute(DragonSlayingStrategy strategy, String expectedResult) {
strategy.execute();
assertEquals(expectedResult, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
private 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();
}
}
}
| 3,589
| 29.948276
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/test/java/com/iluwatar/strategy/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.strategy;
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/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.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.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Spell strategy.
*/
@Slf4j
public class SpellStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
}
}
| 1,594
| 37.902439
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/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.strategy;
import lombok.extern.slf4j.Slf4j;
/**
*
* <p>The Strategy pattern (also known as the policy pattern) is a software design pattern that
* enables an algorithm's behavior to be selected at runtime.</p>
*
* <p>Before Java 8 the Strategies needed to be separate classes forcing the developer
* to write lots of boilerplate code. With modern Java, it is easy to pass behavior
* with method references and lambdas making the code shorter and more readable.</p>
*
* <p>In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing
* object ({@link DragonSlayer}) can alter its behavior by changing its strategy.</p>
*
*/
@Slf4j
public class App {
private static final String RED_DRAGON_EMERGES = "Red dragon emerges.";
private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!";
private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you.";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// GoF Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
var dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
// Java 8 functional implementation Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
dragonSlayer = new DragonSlayer(
() -> LOGGER.info("With your Excalibur you severe the dragon's head!"));
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(() -> LOGGER.info(
"You shoot the dragon with the magical crossbow and it falls dead on the ground!"));
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(() -> LOGGER.info(
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
dragonSlayer.goToBattle();
// Java 8 lambda implementation with enum Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy);
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy);
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy);
dragonSlayer.goToBattle();
}
}
| 3,940
| 41.836957
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.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.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Projectile strategy.
*/
@Slf4j
public class ProjectileStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
}
}
| 1,602
| 39.075
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.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.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Lambda implementation for enum strategy pattern.
*/
@Slf4j
public class LambdaStrategy {
/**
* Enum to demonstrate strategy pattern.
*/
public enum Strategy implements DragonSlayingStrategy {
MeleeStrategy(() -> LOGGER.info(
"With your Excalibur you severe the dragon's head!")),
ProjectileStrategy(() -> LOGGER.info(
"You shoot the dragon with the magical crossbow and it falls dead on the ground!")),
SpellStrategy(() -> LOGGER.info(
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
private final DragonSlayingStrategy dragonSlayingStrategy;
Strategy(DragonSlayingStrategy dragonSlayingStrategy) {
this.dragonSlayingStrategy = dragonSlayingStrategy;
}
@Override
public void execute() {
dragonSlayingStrategy.execute();
}
}
}
| 2,211
| 37.137931
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/DragonSlayer.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.strategy;
/**
* DragonSlayer uses different strategies to slay the dragon.
*/
public class DragonSlayer {
private DragonSlayingStrategy strategy;
public DragonSlayer(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void changeStrategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void goToBattle() {
strategy.execute();
}
}
| 1,706
| 36.108696
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/DragonSlayingStrategy.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.strategy;
/**
* Strategy interface.
*/
@FunctionalInterface
public interface DragonSlayingStrategy {
void execute();
}
| 1,431
| 38.777778
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/strategy/src/main/java/com/iluwatar/strategy/MeleeStrategy.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.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Melee strategy.
*/
@Slf4j
public class MeleeStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("With your Excalibur you sever the dragon's head!");
}
}
| 1,561
| 38.05
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.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.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 28/04/17 - 7:40 AM
*
* @author Stanislav Kapinus
*/
class AdvancedSorceressTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to
* her through the setter's parameter
*/
@Test
void testSmokeEveryThing() throws Exception {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the sorceress is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(tobacco);
advancedSorceress.smoke();
String lastMessage = appender.getLastMessage();
assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), lastMessage);
});
// ... and nothing else is happening.
assertEquals(tobaccos.size(), appender.getLogSize());
}
}
| 2,744
| 32.072289
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.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.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 12/10/15 - 8:40 PM
*
* @author Jeroen Meulemeester
*/
class AdvancedWizardTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test if the {@link AdvancedWizard} smokes whatever instance of {@link Tobacco} is passed to him
* through the constructor parameter
*/
@Test
void testSmokeEveryThing() throws Exception {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco);
advancedWizard.smoke();
String lastMessage = appender.getLastMessage();
assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
});
// ... and nothing else is happening.
assertEquals(tobaccos.size(), appender.getLogSize());
}
}
| 2,701
| 31.95122
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.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.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 12/10/15 - 8:57 PM
*
* @author Jeroen Meulemeester
*/
class GuiceWizardTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him
* through the constructor parameter
*/
@Test
void testSmokeEveryThingThroughConstructor() throws Exception {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final GuiceWizard guiceWizard = new GuiceWizard(tobacco);
guiceWizard.smoke();
String lastMessage = appender.getLastMessage();
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), lastMessage);
});
// ... and nothing else is happening.
assertEquals(tobaccos.size(), appender.getLogSize());
}
/**
* Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him
* through the Guice google inject framework
*/
@Test
void testSmokeEveryThingThroughInjectionFramework() throws Exception {
List<Class<? extends Tobacco>> tobaccos = List.of(
OldTobyTobacco.class,
RivendellTobacco.class,
SecondBreakfastTobacco.class
);
// Configure the tobacco in the injection framework ...
// ... and create a new wizard with it
// Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobaccoClass -> {
final var injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Tobacco.class).to(tobaccoClass);
}
});
final var guiceWizard = injector.getInstance(GuiceWizard.class);
guiceWizard.smoke();
String lastMessage = appender.getLastMessage();
assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), lastMessage);
});
// ... and nothing else is happening.
assertEquals(tobaccos.size(), appender.getLogSize());
}
}
| 3,923
| 33.121739
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.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.dependency.injection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Date: 12/10/15 - 8:26 PM
*
* @author Jeroen Meulemeester
*/
class SimpleWizardTest {
private InMemoryAppender appender;
@BeforeEach
void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@AfterEach
void tearDown() {
appender.stop();
}
/**
* Test if the {@link SimpleWizard} does the only thing it can do: Smoke it's {@link
* OldTobyTobacco}
*/
@Test
void testSmoke() {
final var simpleWizard = new SimpleWizard();
simpleWizard.smoke();
assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
| 2,212
| 32.530303
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/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.dependency.injection;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* 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,815
| 36.833333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/test/java/com/iluwatar/dependency/injection/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.dependency.injection.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
/**
* InMemory Log Appender Util.
*/
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}
| 2,094
| 33.916667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/RivendellTobacco.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.dependency.injection;
/**
* RivendellTobacco concrete {@link Tobacco} implementation.
*/
public class RivendellTobacco extends Tobacco {
}
| 1,447
| 44.25
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/OldTobyTobacco.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.dependency.injection;
/**
* OldTobyTobacco concrete {@link Tobacco} implementation.
*/
public class OldTobyTobacco extends Tobacco {
}
| 1,443
| 44.125
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/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.dependency.injection;
import com.google.inject.Guice;
/**
* Dependency Injection pattern deals with how objects handle their dependencies. The pattern
* implements so called inversion of control principle. Inversion of control has two specific rules:
* - High-level modules should not depend on low-level modules. Both should depend on abstractions.
* - Abstractions should not depend on details. Details should depend on abstractions.
*
* <p>In this example we show you three different wizards. The first one ({@link SimpleWizard}) is
* a naive implementation violating the inversion of control principle. It depends directly on a
* concrete implementation which cannot be changed.
*
* <p>The second and third wizards({@link AdvancedWizard} and {@link AdvancedSorceress}) are more
* flexible. They do not depend on any concrete implementation but abstraction. They utilizes
* Dependency Injection pattern allowing their {@link Tobacco} dependency to be injected through
* constructor ({@link AdvancedWizard}) or setter ({@link AdvancedSorceress}). This way, handling
* the dependency is no longer the wizard's responsibility. It is resolved outside the wizard
* class.
*
* <p>The fourth example takes the pattern a step further. It uses Guice framework for Dependency
* Injection. {@link TobaccoModule} binds a concrete implementation to abstraction. Injector is then
* used to create {@link GuiceWizard} object with correct dependencies.
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var simpleWizard = new SimpleWizard();
simpleWizard.smoke();
var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
advancedWizard.smoke();
var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(new SecondBreakfastTobacco());
advancedSorceress.smoke();
var injector = Guice.createInjector(new TobaccoModule());
var guiceWizard = injector.getInstance(GuiceWizard.class);
guiceWizard.smoke();
}
}
| 3,390
| 45.452055
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Tobacco.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.dependency.injection;
import lombok.extern.slf4j.Slf4j;
/**
* Tobacco abstraction.
*/
@Slf4j
public abstract class Tobacco {
public void smoke(Wizard wizard) {
LOGGER.info("{} smoking {}", wizard.getClass().getSimpleName(),
this.getClass().getSimpleName());
}
}
| 1,588
| 38.725
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/GuiceWizard.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.dependency.injection;
import javax.inject.Inject;
/**
* GuiceWizard implements inversion of control. Its dependencies are injected through its
* constructor by Guice framework.
*/
public class GuiceWizard implements Wizard {
private final Tobacco tobacco;
@Inject
public GuiceWizard(Tobacco tobacco) {
this.tobacco = tobacco;
}
@Override
public void smoke() {
tobacco.smoke(this);
}
}
| 1,720
| 35.617021
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedWizard.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.dependency.injection;
import lombok.RequiredArgsConstructor;
/**
* AdvancedWizard implements inversion of control. It depends on abstraction that can be injected
* through its constructor.
*/
@RequiredArgsConstructor
public class AdvancedWizard implements Wizard {
private final Tobacco tobacco;
@Override
public void smoke() {
tobacco.smoke(this);
}
}
| 1,677
| 38.023256
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/TobaccoModule.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.dependency.injection;
import com.google.inject.AbstractModule;
/**
* Guice module for binding certain concrete {@link Tobacco} implementation.
*/
public class TobaccoModule extends AbstractModule {
@Override
protected void configure() {
bind(Tobacco.class).to(RivendellTobacco.class);
}
}
| 1,609
| 40.282051
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SimpleWizard.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.dependency.injection;
/**
* Naive Wizard implementation violating the inversion of control principle. It should depend on
* abstraction instead.
*/
public class SimpleWizard implements Wizard {
private final OldTobyTobacco tobacco = new OldTobyTobacco();
public void smoke() {
tobacco.smoke(this);
}
}
| 1,623
| 40.641026
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/Wizard.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.dependency.injection;
/**
* Wizard interface.
*/
public interface Wizard {
void smoke();
}
| 1,403
| 39.114286
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/AdvancedSorceress.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.dependency.injection;
import lombok.Setter;
/**
* AdvancedSorceress implements inversion of control. It depends on abstraction that can be injected
* through its setter.
*/
@Setter
public class AdvancedSorceress implements Wizard {
private Tobacco tobacco;
@Override
public void smoke() {
tobacco.smoke(this);
}
}
| 1,638
| 37.116279
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dependency-injection/src/main/java/com/iluwatar/dependency/injection/SecondBreakfastTobacco.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.dependency.injection;
/**
* SecondBreakfastTobacco concrete {@link Tobacco} implementation.
*/
public class SecondBreakfastTobacco extends Tobacco {
}
| 1,459
| 44.625
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.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.module;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* The Module pattern can be considered a Creational pattern and a Structural pattern. It manages
* the creation and organization of other elements, and groups them as the structural pattern does.
* An object that applies this pattern can provide the equivalent of a namespace, providing the
* initialization and finalization process of a static class or a class with static members with
* cleaner, more concise syntax and semantics.
* <p>
* The below example demonstrates a JUnit test for testing two different modules: File Logger and
* Console Logger
*/
@Slf4j
public final class FileLoggerModuleTest {
private static final String OUTPUT_FILE = "output.txt";
private static final String ERROR_FILE = "error.txt";
private static final String MESSAGE = "MESSAGE";
private static final String ERROR = "ERROR";
/**
* This test verify that 'MESSAGE' is perfectly printed in output file
*
* @throws IOException if program is not able to find log files (output.txt and error.txt)
*/
@Test
void testFileMessage() throws IOException {
/* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
/* Print 'Message' in file */
fileLoggerModule.printString(MESSAGE);
/* Test if 'Message' is printed in file */
assertEquals(readFirstLine(OUTPUT_FILE), MESSAGE);
/* Unprepare to cleanup the modules */
fileLoggerModule.unprepare();
}
/**
* This test verify that nothing is printed in output file
*
* @throws IOException if program is not able to find log files (output.txt and error.txt)
*/
@Test
void testNoFileMessage() throws IOException {
/* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
/* Test if nothing is printed in file */
assertNull(readFirstLine(OUTPUT_FILE));
/* Unprepare to cleanup the modules */
fileLoggerModule.unprepare();
}
/**
* This test verify that 'ERROR' is perfectly printed in error file
*
* @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt)
*/
@Test
void testFileErrorMessage() throws FileNotFoundException {
/* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
/* Print 'Error' in file */
fileLoggerModule.printErrorString(ERROR);
/* Test if 'Message' is printed in file */
assertEquals(ERROR, readFirstLine(ERROR_FILE));
/* Un-prepare to cleanup the modules */
fileLoggerModule.unprepare();
}
/**
* This test verify that nothing is printed in error file
*
* @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt)
*/
@Test
void testNoFileErrorMessage() throws FileNotFoundException {
/* Get singleton instance of File Logger Module */
final var fileLoggerModule = FileLoggerModule.getSingleton();
/* Prepare the essential sub modules, to perform the sequence of jobs */
fileLoggerModule.prepare();
/* Test if nothing is printed in file */
assertNull(readFirstLine(ERROR_FILE));
/* Unprepare to cleanup the modules */
fileLoggerModule.unprepare();
}
/**
* Utility method to read first line of a file
*
* @param file as file name to be read
* @return a string value as first line in file
*/
private static String readFirstLine(final String file) {
String firstLine = null;
try (var bufferedReader = new BufferedReader(new FileReader(file))) {
while (bufferedReader.ready()) {
/* Read the line */
firstLine = bufferedReader.readLine();
}
LOGGER.info("ModuleTest::readFirstLine() : firstLine : " + firstLine);
} catch (final IOException e) {
LOGGER.error("ModuleTest::readFirstLine()", e);
}
return firstLine;
}
}
| 5,955
| 33.034286
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/module/src/test/java/com/iluwatar/module/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.module;
import java.io.FileNotFoundException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Module example runs without errors.
*/
final class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow((Executable) App::main);
}
}
| 1,690
| 38.325581
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/module/src/main/java/com/iluwatar/module/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.module;
import java.io.FileNotFoundException;
/**
* The Module pattern can be considered a Creational pattern and a Structural pattern. It manages
* the creation and organization of other elements, and groups them as the structural pattern does.
* An object that applies this pattern can provide the equivalent of a namespace, providing the
* initialization and finalization process of a static class or a class with static members with
* cleaner, more concise syntax and semantics.
*
* <p>The below example demonstrates a use case for testing two different modules: File Logger and
* Console Logger
*/
public class App {
private static final String ERROR = "Error";
private static final String MESSAGE = "Message";
public static FileLoggerModule fileLoggerModule;
public static ConsoleLoggerModule consoleLoggerModule;
/**
* Following method performs the initialization.
*
* @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt)
*/
public static void prepare() throws FileNotFoundException {
/* Create new singleton objects and prepare their modules */
fileLoggerModule = FileLoggerModule.getSingleton().prepare();
consoleLoggerModule = ConsoleLoggerModule.getSingleton().prepare();
}
/**
* Following method performs the finalization.
*/
public static void unprepare() {
/* Close all resources */
fileLoggerModule.unprepare();
consoleLoggerModule.unprepare();
}
/**
* Following method is main executor.
*/
public static void execute() {
/* Send logs on file system */
fileLoggerModule.printString(MESSAGE);
fileLoggerModule.printErrorString(ERROR);
/* Send logs on console */
consoleLoggerModule.printString(MESSAGE);
consoleLoggerModule.printErrorString(ERROR);
}
/**
* Program entry point.
*
* @param args command line args.
* @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt)
*/
public static void main(final String... args) throws FileNotFoundException {
prepare();
execute();
unprepare();
}
}
| 3,517
| 35.645833
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/module/src/main/java/com/iluwatar/module/ConsoleLoggerModule.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.module;
import java.io.PrintStream;
import lombok.extern.slf4j.Slf4j;
/**
* The ConsoleLoggerModule is responsible for showing logs on System Console.
*
* <p>The below example demonstrates a Console logger module, which can print simple and error
* messages in two designated formats
*/
@Slf4j
public final class ConsoleLoggerModule {
private static ConsoleLoggerModule singleton = null;
public PrintStream output = null;
public PrintStream error = null;
private ConsoleLoggerModule() {
}
/**
* Static method to get single instance of class.
*
* @return singleton instance of ConsoleLoggerModule
*/
public static ConsoleLoggerModule getSingleton() {
if (ConsoleLoggerModule.singleton == null) {
ConsoleLoggerModule.singleton = new ConsoleLoggerModule();
}
return ConsoleLoggerModule.singleton;
}
/**
* Following method performs the initialization.
*/
public ConsoleLoggerModule prepare() {
LOGGER.debug("ConsoleLoggerModule::prepare();");
this.output = new PrintStream(System.out);
this.error = new PrintStream(System.err);
return this;
}
/**
* Following method performs the finalization.
*/
public void unprepare() {
if (this.output != null) {
this.output.flush();
this.output.close();
}
if (this.error != null) {
this.error.flush();
this.error.close();
}
LOGGER.debug("ConsoleLoggerModule::unprepare();");
}
/**
* Used to print a message.
*
* @param value will be printed on console
*/
public void printString(final String value) {
this.output.println(value);
}
/**
* Used to print a error message.
*
* @param value will be printed on error console
*/
public void printErrorString(final String value) {
this.error.println(value);
}
}
| 3,140
| 27.044643
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/module/src/main/java/com/iluwatar/module/FileLoggerModule.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.module;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import lombok.extern.slf4j.Slf4j;
/**
* The FileLoggerModule is responsible for showing logs on File System.
*
* <p>The below example demonstrates a File logger module, which can print simple and error
* messages in two designated files
*/
@Slf4j
public final class FileLoggerModule {
private static FileLoggerModule singleton = null;
private static final String OUTPUT_FILE = "output.txt";
private static final String ERROR_FILE = "error.txt";
public PrintStream output = null;
public PrintStream error = null;
private FileLoggerModule() {
}
/**
* Static method to get single instance of class.
*
* @return singleton instance of FileLoggerModule
*/
public static FileLoggerModule getSingleton() {
if (FileLoggerModule.singleton == null) {
FileLoggerModule.singleton = new FileLoggerModule();
}
return FileLoggerModule.singleton;
}
/**
* Following method performs the initialization.
*
* @throws FileNotFoundException if program is not able to find log files (output.txt and
* error.txt)
*/
public FileLoggerModule prepare() throws FileNotFoundException {
LOGGER.debug("FileLoggerModule::prepare();");
this.output = new PrintStream(new FileOutputStream(OUTPUT_FILE));
this.error = new PrintStream(new FileOutputStream(ERROR_FILE));
return this;
}
/**
* Following method performs the finalization.
*/
public void unprepare() {
if (this.output != null) {
this.output.flush();
this.output.close();
}
if (this.error != null) {
this.error.flush();
this.error.close();
}
LOGGER.debug("FileLoggerModule::unprepare();");
}
/**
* Used to print a message.
*
* @param value will be printed in file
*/
public void printString(final String value) {
this.output.println(value);
}
/**
* Used to print a error message.
*
* @param value will be printed on error file
*/
public void printErrorString(final String value) {
this.error.println(value);
}
}
| 3,490
| 28.091667
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.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.async.method.invocation;
import static java.time.Duration.ofMillis;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Date: 12/6/15 - 10:49 AM
*
* @author Jeroen Meulemeester
*/
class ThreadAsyncExecutorTest {
@Captor
private ArgumentCaptor<Optional<Exception>> optionalCaptor;
@Mock
private Callable<Object> task;
@Mock
private AsyncCallback<Object> callback;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)}
*/
@Test
void testSuccessfulTaskWithoutCallback() throws Exception {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var result = new Object();
when(task.call()).thenReturn(result);
final var asyncResult = executor.startProcess(task);
assertNotNull(asyncResult);
asyncResult.await(); // Prevent timing issues, and wait until the result is available
assertTrue(asyncResult.isCompleted());
// Our task should only execute once ...
verify(task, times(1)).call();
// ... and the result should be exactly the same object
assertSame(result, asyncResult.getValue());
});
}
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable,
* AsyncCallback)}
*/
@Test
void testSuccessfulTaskWithCallback() throws Exception {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var result = new Object();
when(task.call()).thenReturn(result);
final var asyncResult = executor.startProcess(task, callback);
assertNotNull(asyncResult);
asyncResult.await(); // Prevent timing issues, and wait until the result is available
assertTrue(asyncResult.isCompleted());
// Our task should only execute once ...
verify(task, times(1)).call();
// ... same for the callback, we expect our object
verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture());
final var optionalException = optionalCaptor.getValue();
assertNotNull(optionalException);
assertFalse(optionalException.isPresent());
// ... and the result should be exactly the same object
assertSame(result, asyncResult.getValue());
});
}
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a
* task takes a while to execute
*/
@Test
void testLongRunningTaskWithoutCallback() throws Exception {
assertTimeout(ofMillis(5000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var result = new Object();
when(task.call()).thenAnswer(i -> {
Thread.sleep(1500);
return result;
});
final var asyncResult = executor.startProcess(task);
assertNotNull(asyncResult);
assertFalse(asyncResult.isCompleted());
try {
asyncResult.getValue();
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
} catch (IllegalStateException e) {
assertNotNull(e.getMessage());
}
// Our task should only execute once, but it can take a while ...
verify(task, timeout(3000).times(1)).call();
// Prevent timing issues, and wait until the result is available
asyncResult.await();
assertTrue(asyncResult.isCompleted());
verifyNoMoreInteractions(task);
// ... and the result should be exactly the same object
assertSame(result, asyncResult.getValue());
});
}
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable,
* AsyncCallback)} when a task takes a while to execute
*/
@Test
void testLongRunningTaskWithCallback() throws Exception {
assertTimeout(ofMillis(5000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var result = new Object();
when(task.call()).thenAnswer(i -> {
Thread.sleep(1500);
return result;
});
final var asyncResult = executor.startProcess(task, callback);
assertNotNull(asyncResult);
assertFalse(asyncResult.isCompleted());
verifyNoMoreInteractions(callback);
try {
asyncResult.getValue();
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
} catch (IllegalStateException e) {
assertNotNull(e.getMessage());
}
// Our task should only execute once, but it can take a while ...
verify(task, timeout(3000).times(1)).call();
verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture());
final var optionalException = optionalCaptor.getValue();
assertNotNull(optionalException);
assertFalse(optionalException.isPresent());
// Prevent timing issues, and wait until the result is available
asyncResult.await();
assertTrue(asyncResult.isCompleted());
verifyNoMoreInteractions(task, callback);
// ... and the result should be exactly the same object
assertSame(result, asyncResult.getValue());
});
}
/**
* Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a
* task takes a while to execute, while waiting on the result using {@link
* ThreadAsyncExecutor#endProcess(AsyncResult)}
*/
@Test
void testEndProcess() throws Exception {
assertTimeout(ofMillis(5000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var result = new Object();
when(task.call()).thenAnswer(i -> {
Thread.sleep(1500);
return result;
});
final var asyncResult = executor.startProcess(task);
assertNotNull(asyncResult);
assertFalse(asyncResult.isCompleted());
try {
asyncResult.getValue();
fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task");
} catch (IllegalStateException e) {
assertNotNull(e.getMessage());
}
assertSame(result, executor.endProcess(asyncResult));
verify(task, times(1)).call();
assertTrue(asyncResult.isCompleted());
// Calling end process a second time while already finished should give the same result
assertSame(result, executor.endProcess(asyncResult));
verifyNoMoreInteractions(task);
});
}
/**
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when
* the callable is 'null'
*/
@Test
void testNullTask() throws Exception {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var asyncResult = executor.startProcess(null);
assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'.");
asyncResult.await(); // Prevent timing issues, and wait until the result is available
assertTrue(asyncResult.isCompleted());
try {
asyncResult.getValue();
fail("Expected ExecutionException with NPE as cause");
} catch (final ExecutionException e) {
assertNotNull(e.getMessage());
assertNotNull(e.getCause());
assertEquals(NullPointerException.class, e.getCause().getClass());
}
});
}
/**
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable,
* AsyncCallback)} when the callable is 'null', but the asynchronous callback is provided
*/
@Test
void testNullTaskWithCallback() throws Exception {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var asyncResult = executor.startProcess(null, callback);
assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'.");
asyncResult.await(); // Prevent timing issues, and wait until the result is available
assertTrue(asyncResult.isCompleted());
verify(callback, times(1)).onComplete(isNull(), optionalCaptor.capture());
final var optionalException = optionalCaptor.getValue();
assertNotNull(optionalException);
assertTrue(optionalException.isPresent());
final var exception = optionalException.get();
assertNotNull(exception);
assertEquals(NullPointerException.class, exception.getClass());
try {
asyncResult.getValue();
fail("Expected ExecutionException with NPE as cause");
} catch (final ExecutionException e) {
assertNotNull(e.getMessage());
assertNotNull(e.getCause());
assertEquals(NullPointerException.class, e.getCause().getClass());
}
});
}
/**
* Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable,
* AsyncCallback)} when both the callable and the asynchronous callback are 'null'
*/
@Test
void testNullTaskWithNullCallback() throws Exception {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var asyncResult = executor.startProcess(null, null);
assertNotNull(
asyncResult,
"The AsyncResult should not be 'null', even though the task and callback were 'null'."
);
asyncResult.await(); // Prevent timing issues, and wait until the result is available
assertTrue(asyncResult.isCompleted());
try {
asyncResult.getValue();
fail("Expected ExecutionException with NPE as cause");
} catch (final ExecutionException e) {
assertNotNull(e.getMessage());
assertNotNull(e.getCause());
assertEquals(NullPointerException.class, e.getCause().getClass());
}
});
}
}
| 12,729
| 35.371429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/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.async.method.invocation;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,805
| 35.12
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/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.async.method.invocation;
import java.util.concurrent.Callable;
import lombok.extern.slf4j.Slf4j;
/**
* In this example, we are launching space rockets and deploying lunar rovers.
*
* <p>The application demonstrates the async method invocation pattern. The key parts of the
* pattern are <code>AsyncResult</code> which is an intermediate container for an asynchronously
* evaluated value, <code>AsyncCallback</code> which can be provided to be executed on task
* completion and <code>AsyncExecutor</code> that manages the execution of the async tasks.
*
* <p>The main method shows example flow of async invocations. The main thread starts multiple
* tasks with variable durations and then continues its own work. When the main thread has done it's
* job it collects the results of the async tasks. Two of the tasks are handled with callbacks,
* meaning the callbacks are executed immediately when the tasks complete.
*
* <p>Noteworthy difference of thread usage between the async results and callbacks is that the
* async results are collected in the main thread but the callbacks are executed within the worker
* threads. This should be noted when working with thread pools.
*
* <p>Java provides its own implementations of async method invocation pattern. FutureTask,
* CompletableFuture and ExecutorService are the real world implementations of this pattern. But due
* to the nature of parallel programming, the implementations are not trivial. This example does not
* take all possible scenarios into account but rather provides a simple version that helps to
* understand the pattern.
*
* @see AsyncResult
* @see AsyncCallback
* @see AsyncExecutor
* @see java.util.concurrent.FutureTask
* @see java.util.concurrent.CompletableFuture
* @see java.util.concurrent.ExecutorService
*/
@Slf4j
public class App {
private static final String ROCKET_LAUNCH_LOG_PATTERN = "Space rocket <%s> launched successfully";
/**
* Program entry point.
*/
public static void main(String[] args) throws Exception {
// construct a new executor that will run async tasks
var executor = new ThreadAsyncExecutor();
// start few async tasks with varying processing times, two last with callback handlers
final var asyncResult1 = executor.startProcess(lazyval(10, 500));
final var asyncResult2 = executor.startProcess(lazyval("test", 300));
final var asyncResult3 = executor.startProcess(lazyval(50L, 700));
final var asyncResult4 = executor.startProcess(lazyval(20, 400),
callback("Deploying lunar rover"));
final var asyncResult5 =
executor.startProcess(lazyval("callback", 600), callback("Deploying lunar rover"));
// emulate processing in the current thread while async tasks are running in their own threads
Thread.sleep(350); // Oh boy, we are working hard here
log("Mission command is sipping coffee");
// wait for completion of the tasks
final var result1 = executor.endProcess(asyncResult1);
final var result2 = executor.endProcess(asyncResult2);
final var result3 = executor.endProcess(asyncResult3);
asyncResult4.await();
asyncResult5.await();
// log the results of the tasks, callbacks log immediately when complete
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result1));
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result2));
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, result3));
}
/**
* Creates a callable that lazily evaluates to given value with artificial delay.
*
* @param value value to evaluate
* @param delayMillis artificial delay in milliseconds
* @return new callable for lazy evaluation
*/
private static <T> Callable<T> lazyval(T value, long delayMillis) {
return () -> {
Thread.sleep(delayMillis);
log(String.format(ROCKET_LAUNCH_LOG_PATTERN, value));
return value;
};
}
/**
* Creates a simple callback that logs the complete status of the async result.
*
* @param name callback name
* @return new async callback
*/
private static <T> AsyncCallback<T> callback(String name) {
return (value, ex) -> {
if (ex.isPresent()) {
log(name + " failed: " + ex.map(Exception::getMessage).orElse(""));
} else {
log(name + " <" + value + ">");
}
};
}
private static void log(String msg) {
LOGGER.info(msg);
}
}
| 5,690
| 41.470149
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.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.async.method.invocation;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Implementation of async executor that creates a new thread for every task.
*/
public class ThreadAsyncExecutor implements AsyncExecutor {
/**
* Index for thread naming.
*/
private final AtomicInteger idx = new AtomicInteger(0);
@Override
public <T> AsyncResult<T> startProcess(Callable<T> task) {
return startProcess(task, null);
}
@Override
public <T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback) {
var result = new CompletableResult<>(callback);
new Thread(() -> {
try {
result.setValue(task.call());
} catch (Exception ex) {
result.setException(ex);
}
}, "executor-" + idx.incrementAndGet()).start();
return result;
}
@Override
public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException,
InterruptedException {
if (!asyncResult.isCompleted()) {
asyncResult.await();
}
return asyncResult.getValue();
}
/**
* Simple implementation of async result that allows completing it successfully with a value or
* exceptionally with an exception. A really simplified version from its real life cousins
* FutureTask and CompletableFuture.
*
* @see java.util.concurrent.FutureTask
* @see java.util.concurrent.CompletableFuture
*/
private static class CompletableResult<T> implements AsyncResult<T> {
static final int RUNNING = 1;
static final int FAILED = 2;
static final int COMPLETED = 3;
final Object lock;
final Optional<AsyncCallback<T>> callback;
volatile int state = RUNNING;
T value;
Exception exception;
CompletableResult(AsyncCallback<T> callback) {
this.lock = new Object();
this.callback = Optional.ofNullable(callback);
}
/**
* Sets the value from successful execution and executes callback if available. Notifies any
* thread waiting for completion.
*
* @param value value of the evaluated task
*/
void setValue(T value) {
this.value = value;
this.state = COMPLETED;
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.empty()));
synchronized (lock) {
lock.notifyAll();
}
}
/**
* Sets the exception from failed execution and executes callback if available. Notifies any
* thread waiting for completion.
*
* @param exception exception of the failed task
*/
void setException(Exception exception) {
this.exception = exception;
this.state = FAILED;
this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception)));
synchronized (lock) {
lock.notifyAll();
}
}
@Override
public boolean isCompleted() {
return state > RUNNING;
}
@Override
public T getValue() throws ExecutionException {
if (state == COMPLETED) {
return value;
} else if (state == FAILED) {
throw new ExecutionException(exception);
} else {
throw new IllegalStateException("Execution not completed yet");
}
}
@Override
public void await() throws InterruptedException {
synchronized (lock) {
while (!isCompleted()) {
lock.wait();
}
}
}
}
}
| 4,747
| 30.443709
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.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.async.method.invocation;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* AsyncExecutor interface.
*/
public interface AsyncExecutor {
/**
* Starts processing of an async task. Returns immediately with async result.
*
* @param task task to be executed asynchronously
* @return async result for the task
*/
<T> AsyncResult<T> startProcess(Callable<T> task);
/**
* Starts processing of an async task. Returns immediately with async result. Executes callback
* when the task is completed.
*
* @param task task to be executed asynchronously
* @param callback callback to be executed on task completion
* @return async result for the task
*/
<T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
/**
* Ends processing of an async task. Blocks the current thread if necessary and returns the
* evaluated value of the completed task.
*
* @param asyncResult async result of a task
* @return evaluated value of the completed task
* @throws ExecutionException if execution has failed, containing the root cause
* @throws InterruptedException if the execution is interrupted
*/
<T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
}
| 2,620
| 39.953125
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.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.async.method.invocation;
import java.util.concurrent.ExecutionException;
/**
* AsyncResult interface.
*
* @param <T> parameter returned when getValue is invoked
*/
public interface AsyncResult<T> {
/**
* Status of the async task execution.
*
* @return <code>true</code> if execution is completed or failed
*/
boolean isCompleted();
/**
* Gets the value of completed async task.
*
* @return evaluated value or throws ExecutionException if execution has failed
* @throws ExecutionException if execution has failed, containing the root cause
* @throws IllegalStateException if execution is not completed
*/
T getValue() throws ExecutionException;
/**
* Blocks the current thread until the async task is completed.
*
* @throws InterruptedException if the execution is interrupted
*/
void await() throws InterruptedException;
}
| 2,194
| 36.20339
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.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.async.method.invocation;
import java.util.Optional;
/**
* AsyncCallback interface.
*
* @param <T> Type of Result
*/
public interface AsyncCallback<T> {
/**
* Complete handler which is executed when async task is completed or fails execution.
*
* @param value the evaluated value from async task, undefined when execution fails
* @param ex empty value if execution succeeds, some exception if executions fails
*/
void onComplete(T value, Optional<Exception> ex);
}
| 1,798
| 39.886364
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/registry/src/test/java/com/iluwatar/registry/CustomerRegistryTest.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.registry;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
class CustomerRegistryTest {
private static CustomerRegistry customerRegistry;
@BeforeAll
public static void setUp() {
customerRegistry = CustomerRegistry.getInstance();
}
@Test
void shouldBeAbleToAddAndQueryCustomerObjectFromRegistry() {
Customer john = new Customer("1", "john");
Customer julia = new Customer("2", "julia");
customerRegistry.addCustomer(john);
customerRegistry.addCustomer(julia);
Customer customerWithId1 = customerRegistry.getCustomer("1");
assertNotNull(customerWithId1);
assertEquals("1", customerWithId1.id());
assertEquals("john", customerWithId1.name());
Customer customerWithId2 = customerRegistry.getCustomer("2");
assertNotNull(customerWithId2);
assertEquals("2", customerWithId2.id());
assertEquals("julia", customerWithId2.name());
}
@Test
void shouldReturnNullWhenQueriedCustomerIsNotInRegistry() {
Customer customerWithId5 = customerRegistry.getCustomer("5");
assertNull(customerWithId5);
}
}
| 2,588
| 37.073529
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/registry/src/main/java/com/iluwatar/registry/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.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* In Registry pattern, objects of a single class are stored and provide a global point of access to them.
* Note that there is no restriction on the number of objects.
*
* <p> The given example {@link CustomerRegistry} represents the registry used to store and
* access {@link Customer} objects. </p>
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
CustomerRegistry customerRegistry = CustomerRegistry.getInstance();
var john = new Customer("1", "John");
customerRegistry.addCustomer(john);
var julia = new Customer("2", "Julia");
customerRegistry.addCustomer(julia);
LOGGER.info("John {}", customerRegistry.getCustomer("1"));
LOGGER.info("Julia {}", customerRegistry.getCustomer("2"));
}
}
| 2,281
| 37.677966
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/registry/src/main/java/com/iluwatar/registry/CustomerRegistry.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.registry;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* CustomerRegistry class used to store/access {@link Customer} objects.
*/
public final class CustomerRegistry {
private static final CustomerRegistry instance = new CustomerRegistry();
public static CustomerRegistry getInstance() {
return instance;
}
private final Map<String, Customer> customerMap;
private CustomerRegistry() {
customerMap = new ConcurrentHashMap<>();
}
public Customer addCustomer(Customer customer) {
return customerMap.put(customer.id(), customer);
}
public Customer getCustomer(String id) {
return customerMap.get(id);
}
}
| 1,981
| 34.392857
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/registry/src/main/java/com/iluwatar/registry/Customer.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.registry;
/**
* Customer entity used in registry pattern example.
*/
public record Customer(String id, String name) {
@Override
public String toString() {
return "Customer{"
+ "id='" + id + '\''
+ ", name='" + name + '\''
+ '}';
}
}
| 1,576
| 38.425
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.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.prototype;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Date: 12/28/15 - 8:45 PM
*
* @param <P> Prototype
* @author Jeroen Meulemeester
*/
class PrototypeTest<P extends Prototype<P>> {
static Collection<Object[]> dataProvider() {
return List.of(
new Object[]{new OrcBeast("axe"), "Orcish wolf attacks with axe"},
new Object[]{new OrcMage("sword"), "Orcish mage attacks with sword"},
new Object[]{new OrcWarlord("laser"), "Orcish warlord attacks with laser"},
new Object[]{new ElfBeast("cooking"), "Elven eagle helps in cooking"},
new Object[]{new ElfMage("cleaning"), "Elven mage helps in cleaning"},
new Object[]{new ElfWarlord("protecting"), "Elven warlord helps in protecting"}
);
}
@ParameterizedTest
@MethodSource("dataProvider")
void testPrototype(P testedPrototype, String expectedToString) {
assertEquals(expectedToString, testedPrototype.toString());
final var clone = testedPrototype.copy();
assertNotNull(clone);
assertNotSame(clone, testedPrototype);
assertSame(testedPrototype.getClass(), clone.getClass());
assertEquals(clone, testedPrototype);
}
}
| 2,834
| 40.691176
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/test/java/com/iluwatar/prototype/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.prototype;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* 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/prototype/src/main/java/com/iluwatar/prototype/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.prototype;
import lombok.extern.slf4j.Slf4j;
/**
* The Prototype pattern is a creational design pattern in software development. It is used when the
* type of objects to create is determined by a prototypical instance, which is cloned to produce
* new objects. This pattern is used to: - avoid subclasses of an object creator in the client
* application, like the abstract factory pattern, does. - avoid the inherent cost of creating a new
* object in the standard way (e.g., using the 'new' keyword)
*
* <p>In this example we have a factory class ({@link HeroFactoryImpl}) producing objects by
* cloning the existing ones. The factory's prototype objects are given as constructor parameters.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var factory = new HeroFactoryImpl(
new ElfMage("cooking"),
new ElfWarlord("cleaning"),
new ElfBeast("protecting")
);
var mage = factory.createMage();
var warlord = factory.createWarlord();
var beast = factory.createBeast();
LOGGER.info(mage.toString());
LOGGER.info(warlord.toString());
LOGGER.info(beast.toString());
factory = new HeroFactoryImpl(
new OrcMage("axe"),
new OrcWarlord("sword"),
new OrcBeast("laser")
);
mage = factory.createMage();
warlord = factory.createWarlord();
beast = factory.createBeast();
LOGGER.info(mage.toString());
LOGGER.info(warlord.toString());
LOGGER.info(beast.toString());
}
}
| 2,887
| 38.561644
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* ElfWarlord.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class ElfWarlord extends Warlord {
private final String helpType;
public ElfWarlord(ElfWarlord elfWarlord) {
super(elfWarlord);
this.helpType = elfWarlord.helpType;
}
@Override
public String toString() {
return "Elven warlord helps in " + helpType;
}
}
| 1,762
| 34.979592
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/OrcBeast.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcBeast.
*/
@EqualsAndHashCode(callSuper = false)
@RequiredArgsConstructor
public class OrcBeast extends Beast {
private final String weapon;
public OrcBeast(OrcBeast orcBeast) {
super(orcBeast);
this.weapon = orcBeast.weapon;
}
@Override
public String toString() {
return "Orcish wolf attacks with " + weapon;
}
}
| 1,742
| 33.86
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/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.prototype;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
/**
* Prototype.
*/
@Slf4j
public abstract class Prototype<T> implements Cloneable {
/**
* Object a shallow copy of this object or null if this object is not Cloneable.
*/
@SuppressWarnings("unchecked")
@SneakyThrows
public T copy() {
return (T) super.clone();
}
}
| 1,668
| 36.088889
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/Warlord.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* Warlord.
*/
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public abstract class Warlord extends Prototype<Warlord> {
public Warlord(Warlord source) {
}
}
| 1,563
| 37.146341
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/ElfMage.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* ElfMage.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class ElfMage extends Mage {
private final String helpType;
public ElfMage(ElfMage elfMage) {
super(elfMage);
this.helpType = elfMage.helpType;
}
@Override
public String toString() {
return "Elven mage helps in " + helpType;
}
}
| 1,736
| 33.74
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/HeroFactoryImpl.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.prototype;
import lombok.RequiredArgsConstructor;
/**
* Concrete factory class.
*/
@RequiredArgsConstructor
public class HeroFactoryImpl implements HeroFactory {
private final Mage mage;
private final Warlord warlord;
private final Beast beast;
/**
* Create mage.
*/
public Mage createMage() {
return mage.copy();
}
/**
* Create warlord.
*/
public Warlord createWarlord() {
return warlord.copy();
}
/**
* Create beast.
*/
public Beast createBeast() {
return beast.copy();
}
}
| 1,844
| 29.245902
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/Beast.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* Beast.
*/
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public abstract class Beast extends Prototype<Beast> {
public Beast(Beast source) {
}
}
| 1,553
| 36.902439
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/Mage.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* Mage.
*/
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public abstract class Mage extends Prototype<Mage> {
public Mage(Mage source) {
}
}
| 1,548
| 36.780488
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/ElfBeast.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* ElfBeast.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class ElfBeast extends Beast {
private final String helpType;
public ElfBeast(ElfBeast elfBeast) {
super(elfBeast);
this.helpType = elfBeast.helpType;
}
@Override
public String toString() {
return "Elven eagle helps in " + helpType;
}
}
| 1,745
| 33.92
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/OrcMage.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcMage.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class OrcMage extends Mage {
private final String weapon;
public OrcMage(OrcMage orcMage) {
super(orcMage);
this.weapon = orcMage.weapon;
}
@Override
public String toString() {
return "Orcish mage attacks with " + weapon;
}
}
| 1,733
| 33.68
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/HeroFactory.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.prototype;
/**
* Interface for the factory class.
*/
public interface HeroFactory {
Mage createMage();
Warlord createWarlord();
Beast createBeast();
}
| 1,469
| 36.692308
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.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.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcWarlord.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class OrcWarlord extends Warlord {
private final String weapon;
public OrcWarlord(OrcWarlord orcWarlord) {
super(orcWarlord);
this.weapon = orcWarlord.weapon;
}
@Override
public String toString() {
return "Orcish warlord attacks with " + weapon;
}
}
| 1,760
| 34.22
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.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.objectmother.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.iluwatar.objectmother.King;
import com.iluwatar.objectmother.Queen;
import com.iluwatar.objectmother.RoyaltyObjectMother;
import org.junit.jupiter.api.Test;
/**
* Test Generation of Royalty Types using the object-mother
*/
class RoyaltyObjectMotherTest {
@Test
void unsuccessfulKingFlirt() {
var soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing();
var flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
soberUnhappyKing.flirt(flirtyQueen);
assertFalse(soberUnhappyKing.isHappy());
}
@Test
void queenIsBlockingFlirtCauseDrunkKing() {
var drunkUnhappyKing = RoyaltyObjectMother.createDrunkKing();
var notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
drunkUnhappyKing.flirt(notFlirtyQueen);
assertFalse(drunkUnhappyKing.isHappy());
}
@Test
void queenIsBlockingFlirt() {
var soberHappyKing = RoyaltyObjectMother.createHappyKing();
var notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
soberHappyKing.flirt(notFlirtyQueen);
assertFalse(soberHappyKing.isHappy());
}
@Test
void successfullKingFlirt() {
var soberHappyKing = RoyaltyObjectMother.createHappyKing();
var flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
soberHappyKing.flirt(flirtyQueen);
assertTrue(soberHappyKing.isHappy());
}
@Test
void testQueenType() {
var flirtyQueen = RoyaltyObjectMother.createFlirtyQueen();
var notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen();
assertEquals(flirtyQueen.getClass(), Queen.class);
assertEquals(notFlirtyQueen.getClass(), Queen.class);
}
@Test
void testKingType() {
var drunkKing = RoyaltyObjectMother.createDrunkKing();
var happyDrunkKing = RoyaltyObjectMother.createHappyDrunkKing();
var happyKing = RoyaltyObjectMother.createHappyKing();
var soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing();
assertEquals(drunkKing.getClass(), King.class);
assertEquals(happyDrunkKing.getClass(), King.class);
assertEquals(happyKing.getClass(), King.class);
assertEquals(soberUnhappyKing.getClass(), King.class);
}
}
| 3,644
| 38.193548
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/object-mother/src/main/java/com/iluwatar/objectmother/RoyaltyObjectMother.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.objectmother;
/**
* Object Mother Pattern generating Royalty Types.
*/
public final class RoyaltyObjectMother {
/**
* Method to create a sober and unhappy king. The standard parameters are set.
*
* @return An instance of {@link com.iluwatar.objectmother.King} with the standard properties.
*/
public static King createSoberUnhappyKing() {
return new King();
}
/**
* Method of the object mother to create a drunk king.
*
* @return A drunk {@link com.iluwatar.objectmother.King}.
*/
public static King createDrunkKing() {
var king = new King();
king.makeDrunk();
return king;
}
/**
* Method to create a happy king.
*
* @return A happy {@link com.iluwatar.objectmother.King}.
*/
public static King createHappyKing() {
var king = new King();
king.makeHappy();
return king;
}
/**
* Method to create a happy and drunk king.
*
* @return A drunk and happy {@link com.iluwatar.objectmother.King}.
*/
public static King createHappyDrunkKing() {
var king = new King();
king.makeHappy();
king.makeDrunk();
return king;
}
/**
* Method to create a flirty queen.
*
* @return A flirty {@link com.iluwatar.objectmother.Queen}.
*/
public static Queen createFlirtyQueen() {
var queen = new Queen();
queen.setFlirtiness(true);
return queen;
}
/**
* Method to create a not flirty queen.
*
* @return A not flirty {@link com.iluwatar.objectmother.Queen}.
*/
public static Queen createNotFlirtyQueen() {
return new Queen();
}
}
| 2,886
| 29.389474
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/object-mother/src/main/java/com/iluwatar/objectmother/Royalty.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.objectmother;
/**
* Interface contracting Royalty Behaviour.
*/
public interface Royalty {
void makeDrunk();
void makeSober();
void makeHappy();
void makeUnhappy();
}
| 1,486
| 37.128205
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/object-mother/src/main/java/com/iluwatar/objectmother/Queen.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.objectmother;
/**
* Defines all attributes and behaviour related to the Queen.
*/
public class Queen implements Royalty {
private boolean isDrunk = false;
private boolean isHappy = false;
private boolean isFlirty = false;
@Override
public void makeDrunk() {
isDrunk = true;
}
@Override
public void makeSober() {
isDrunk = false;
}
@Override
public void makeHappy() {
isHappy = true;
}
@Override
public void makeUnhappy() {
isHappy = false;
}
public boolean isFlirty() {
return isFlirty;
}
public void setFlirtiness(boolean flirtiness) {
this.isFlirty = flirtiness;
}
/**
* Method which is called when the king is flirting to a queen.
*
* @param king King who initialized the flirt.
* @return A value which describes if the flirt was successful or not.
*/
public boolean getFlirted(King king) {
return this.isFlirty && king.isHappy && !king.isDrunk;
}
}
| 2,255
| 29.90411
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/object-mother/src/main/java/com/iluwatar/objectmother/King.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.objectmother;
/**
* Defines all attributes and behaviour related to the King.
*/
public class King implements Royalty {
boolean isDrunk = false;
boolean isHappy = false;
@Override
public void makeDrunk() {
isDrunk = true;
}
@Override
public void makeSober() {
isDrunk = false;
}
@Override
public void makeHappy() {
isHappy = true;
}
@Override
public void makeUnhappy() {
isHappy = false;
}
public boolean isHappy() {
return isHappy;
}
/**
* Method to flirt to a queen.
*
* @param queen Queen which should be flirted.
*/
public void flirt(Queen queen) {
var flirtStatus = queen.getFlirted(this);
if (!flirtStatus) {
this.makeUnhappy();
} else {
this.makeHappy();
}
}
}
| 2,081
| 27.520548
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/test/java/com/iluwatar/eda/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.eda;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Event Driven Architecture example runs without errors.
*/
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,851
| 37.583333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.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.eda.event;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.iluwatar.eda.model.User;
import org.junit.jupiter.api.Test;
/**
* {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour.
*/
class UserCreatedEventTest {
/**
* This unit test should correctly return the {@link AbstractEvent} class type when calling the
* {@link AbstractEvent#getType() getType} method.
*/
@Test
void testGetEventType() {
var user = new User("iluwatar");
var userCreatedEvent = new UserCreatedEvent(user);
assertEquals(UserCreatedEvent.class, userCreatedEvent.getType());
}
}
| 1,940
| 39.4375
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.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.eda.framework;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import com.iluwatar.eda.event.UserCreatedEvent;
import com.iluwatar.eda.event.UserUpdatedEvent;
import com.iluwatar.eda.handler.UserCreatedEventHandler;
import com.iluwatar.eda.handler.UserUpdatedEventHandler;
import com.iluwatar.eda.model.User;
import org.junit.jupiter.api.Test;
/**
* Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour
*/
class EventDispatcherTest {
/**
* This unit test should register events and event handlers correctly with the event dispatcher
* and events should be dispatched accordingly.
*/
@Test
void testEventDriverPattern() {
var dispatcher = spy(new EventDispatcher());
var userCreatedEventHandler = spy(new UserCreatedEventHandler());
var userUpdatedEventHandler = spy(new UserUpdatedEventHandler());
dispatcher.registerHandler(UserCreatedEvent.class, userCreatedEventHandler);
dispatcher.registerHandler(UserUpdatedEvent.class, userUpdatedEventHandler);
var user = new User("iluwatar");
var userCreatedEvent = new UserCreatedEvent(user);
var userUpdatedEvent = new UserUpdatedEvent(user);
//fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked.
dispatcher.dispatch(userCreatedEvent);
verify(userCreatedEventHandler).onEvent(userCreatedEvent);
verify(dispatcher).dispatch(userCreatedEvent);
//fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked.
dispatcher.dispatch(userUpdatedEvent);
verify(userUpdatedEventHandler).onEvent(userUpdatedEvent);
verify(dispatcher).dispatch(userUpdatedEvent);
}
}
| 3,011
| 40.833333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/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.eda;
import com.iluwatar.eda.event.UserCreatedEvent;
import com.iluwatar.eda.event.UserUpdatedEvent;
import com.iluwatar.eda.framework.Event;
import com.iluwatar.eda.framework.EventDispatcher;
import com.iluwatar.eda.handler.UserCreatedEventHandler;
import com.iluwatar.eda.handler.UserUpdatedEventHandler;
import com.iluwatar.eda.model.User;
/**
* An event-driven architecture (EDA) is a framework that orchestrates behavior around the
* production, detection and consumption of events as well as the responses they evoke. An event is
* any identifiable occurrence that has significance for system hardware or software.
*
* <p>The example below uses an {@link EventDispatcher} to link/register {@link Event} objects to
* their respective handlers once an {@link Event} is dispatched, it's respective handler is invoked
* and the {@link Event} is handled accordingly.
*/
public class App {
/**
* Once the {@link EventDispatcher} is initialised, handlers related to specific events have to be
* made known to the dispatcher by registering them. In this case the {@link UserCreatedEvent} is
* bound to the UserCreatedEventHandler, whilst the {@link UserUpdatedEvent} is bound to the
* {@link UserUpdatedEventHandler}. The dispatcher can now be called to dispatch specific events.
* When a user is saved, the {@link UserCreatedEvent} can be dispatched. On the other hand, when a
* user is updated, {@link UserUpdatedEvent} can be dispatched.
*/
public static void main(String[] args) {
var dispatcher = new EventDispatcher();
dispatcher.registerHandler(UserCreatedEvent.class, new UserCreatedEventHandler());
dispatcher.registerHandler(UserUpdatedEvent.class, new UserUpdatedEventHandler());
var user = new User("iluwatar");
dispatcher.dispatch(new UserCreatedEvent(user));
dispatcher.dispatch(new UserUpdatedEvent(user));
}
}
| 3,194
| 47.409091
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserCreatedEvent.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.eda.event;
import com.iluwatar.eda.model.User;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* The {@link UserCreatedEvent} should be dispatched whenever a user has been created.
* This class can be extended to contain details about the user has been created.
* In this example, the entire {@link User} object is passed on as data with the event.
*/
@RequiredArgsConstructor
@Getter
public class UserCreatedEvent extends AbstractEvent {
private final User user;
}
| 1,797
| 41.809524
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/event/UserUpdatedEvent.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.eda.event;
import com.iluwatar.eda.model.User;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* The {@link UserUpdatedEvent} should be dispatched whenever a user has been updated.
* This class can be extended to contain details about the user has been updated.
* In this example, the entire {@link User} object is passed on as data with the event.
*/
@RequiredArgsConstructor
@Getter
public class UserUpdatedEvent extends AbstractEvent {
private final User user;
}
| 1,797
| 41.809524
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/event/AbstractEvent.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.eda.event;
import com.iluwatar.eda.framework.Event;
import com.iluwatar.eda.framework.EventDispatcher;
/**
* The {@link AbstractEvent} class serves as a base class for defining custom events happening with
* your system. In this example we have two types of events defined.
* <ul>
* <li>{@link UserCreatedEvent} - used when a user is created</li>
* <li>{@link UserUpdatedEvent} - used when a user is updated</li>
* </ul>
* Events can be distinguished using the {@link #getType() getType} method.
*/
public abstract class AbstractEvent implements Event {
/**
* Returns the event type as a {@link Class} object In this example, this method is used by the
* {@link EventDispatcher} to dispatch events depending on their type.
*
* @return the AbstractEvent type as a {@link Class}.
*/
public Class<? extends Event> getType() {
return getClass();
}
}
| 2,190
| 42.82
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserUpdatedEventHandler.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.eda.handler;
import com.iluwatar.eda.event.UserUpdatedEvent;
import com.iluwatar.eda.framework.Handler;
import lombok.extern.slf4j.Slf4j;
/**
* Handles the {@link UserUpdatedEvent} message.
*/
@Slf4j
public class UserUpdatedEventHandler implements Handler<UserUpdatedEvent> {
@Override
public void onEvent(UserUpdatedEvent event) {
LOGGER.info("User '{}' has been Updated!", event.getUser().getUsername());
}
}
| 1,731
| 40.238095
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/handler/UserCreatedEventHandler.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.eda.handler;
import com.iluwatar.eda.event.UserCreatedEvent;
import com.iluwatar.eda.framework.Handler;
import lombok.extern.slf4j.Slf4j;
/**
* Handles the {@link UserCreatedEvent} message.
*/
@Slf4j
public class UserCreatedEventHandler implements Handler<UserCreatedEvent> {
@Override
public void onEvent(UserCreatedEvent event) {
LOGGER.info("User '{}' has been Created!", event.getUser().getUsername());
}
}
| 1,732
| 39.302326
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/model/User.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.eda.model;
import com.iluwatar.eda.event.UserCreatedEvent;
import com.iluwatar.eda.event.UserUpdatedEvent;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* This {@link User} class is a basic pojo used to demonstrate user data sent along with the {@link
* UserCreatedEvent} and {@link UserUpdatedEvent} events.
*/
@RequiredArgsConstructor
@Getter
public class User {
private final String username;
}
| 1,730
| 40.214286
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Event.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.eda.framework;
/**
* A {@link Event} is an object with a specific type that is associated to a specific {@link
* Handler}.
*/
public interface Event {
/**
* Returns the message type as a {@link Class} object. In this example the message type is used to
* handle events by their type.
*
* @return the message type as a {@link Class}.
*/
Class<? extends Event> getType();
}
| 1,701
| 40.512195
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/EventDispatcher.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.eda.framework;
import java.util.HashMap;
import java.util.Map;
/**
* Handles the routing of {@link Event} messages to associated handlers. A {@link HashMap} is used
* to store the association between events and their respective handlers.
*/
public class EventDispatcher {
private final Map<Class<? extends Event>, Handler<? extends Event>> handlers;
public EventDispatcher() {
handlers = new HashMap<>();
}
/**
* Links an {@link Event} to a specific {@link Handler}.
*
* @param eventType The {@link Event} to be registered
* @param handler The {@link Handler} that will be handling the {@link Event}
*/
public <E extends Event> void registerHandler(
Class<E> eventType,
Handler<E> handler
) {
handlers.put(eventType, handler);
}
/**
* Dispatches an {@link Event} depending on its type.
*
* @param event The {@link Event} to be dispatched
*/
@SuppressWarnings("unchecked")
public <E extends Event> void dispatch(E event) {
var handler = (Handler<E>) handlers.get(event.getClass());
if (handler != null) {
handler.onEvent(event);
}
}
}
| 2,438
| 34.347826
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/event-driven-architecture/src/main/java/com/iluwatar/eda/framework/Handler.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.eda.framework;
/**
* This interface can be implemented to handle different types of messages. Every handler is
* responsible for a single of type message
*
* @param <E> Handler can handle events of type E
*/
public interface Handler<E extends Event> {
/**
* The onEvent method should implement and handle behavior related to the event. This can be as
* simple as calling another service to handle the event on publishing the event in a queue to be
* consumed by other sub systems.
*
* @param event the {@link Event} object to be handled.
*/
void onEvent(E event);
}
| 1,900
| 42.204545
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/test/java/com/iluwatar/separatedinterface/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.separatedinterface;
import org.junit.jupiter.api.Test;
import com.iluwatar.separatedinterface.App;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test.
*/
class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
| 1,631
| 37.857143
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/test/java/com/iluwatar/separatedinterface/invoice/InvoiceGeneratorTest.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.separatedinterface.invoice;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class InvoiceGeneratorTest {
private InvoiceGenerator target;
@Test
void testGenerateTax() {
var productCost = 50.0;
var tax = 10.0;
TaxCalculator taxCalculatorMock = mock(TaxCalculator.class);
doReturn(tax).when(taxCalculatorMock).calculate(productCost);
target = new InvoiceGenerator(productCost, taxCalculatorMock);
Assertions.assertEquals(target.getAmountWithTax(), productCost + tax);
verify(taxCalculatorMock, times(1)).calculate(productCost);
}
}
| 2,074
| 38.150943
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculatorTest.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.separatedinterface.taxes;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ForeignTaxCalculatorTest {
private ForeignTaxCalculator target;
@Test
void testTaxCalculation() {
target = new ForeignTaxCalculator();
var tax = target.calculate(100.0);
Assertions.assertEquals(tax, 60.0);
}
}
| 1,649
| 37.372093
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/test/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculatorTest.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.separatedinterface.taxes;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class DomesticTaxCalculatorTest {
private DomesticTaxCalculator target;
@Test
void testTaxCalculation() {
target = new DomesticTaxCalculator();
var tax = target.calculate(100.0);
Assertions.assertEquals(tax, 20.0);
}
}
| 1,652
| 37.44186
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/main/java/com/iluwatar/separatedinterface/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.separatedinterface;
import com.iluwatar.separatedinterface.invoice.InvoiceGenerator;
import com.iluwatar.separatedinterface.taxes.DomesticTaxCalculator;
import com.iluwatar.separatedinterface.taxes.ForeignTaxCalculator;
import lombok.extern.slf4j.Slf4j;
/**
* <p>The Separated Interface pattern encourages to separate the interface definition and
* implementation in different packages. This allows the client to be completely unaware of the
* implementation.</p>
*
* <p>In this class the {@link InvoiceGenerator} class is injected with different instances of
* {@link com.iluwatar.separatedinterface.invoice.TaxCalculator} implementations located in separate
* packages, to receive different responses for both of the implementations.</p>
*/
@Slf4j
public class App {
public static final double PRODUCT_COST = 50.0;
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
//Create the invoice generator with product cost as 50 and foreign product tax
var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST,
new ForeignTaxCalculator());
LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax());
//Create the invoice generator with product cost as 50 and domestic product tax
var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator());
LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax());
}
}
| 2,829
| 44.645161
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/TaxCalculator.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.separatedinterface.invoice;
/**
* TaxCalculator interface to demonstrate The Separated Interface pattern.
*/
public interface TaxCalculator {
double calculate(double amount);
}
| 1,489
| 41.571429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/main/java/com/iluwatar/separatedinterface/invoice/InvoiceGenerator.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.separatedinterface.invoice;
/**
* InvoiceGenerator class generates an invoice, accepting the product cost and calculating the total
* price payable inclusive tax (calculated by {@link TaxCalculator}).
*
*/
public record InvoiceGenerator(double amount, TaxCalculator taxCalculator) {
/** TaxCalculator description:
* The TaxCalculator interface to calculate the payable tax.
* Amount description:
* The base product amount without tax.
*/
public double getAmountWithTax() {
return amount + taxCalculator.calculate(amount);
}
}
| 1,858
| 43.261905
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/ForeignTaxCalculator.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.separatedinterface.taxes;
import com.iluwatar.separatedinterface.invoice.TaxCalculator;
/**
* TaxCalculator for foreign goods with 60% tax.
*/
public class ForeignTaxCalculator implements TaxCalculator {
public static final double TAX_PERCENTAGE = 60;
@Override
public double calculate(double amount) {
return amount * TAX_PERCENTAGE / 100.0;
}
}
| 1,671
| 38.809524
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/separated-interface/src/main/java/com/iluwatar/separatedinterface/taxes/DomesticTaxCalculator.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.separatedinterface.taxes;
import com.iluwatar.separatedinterface.invoice.TaxCalculator;
/**
* TaxCalculator for Domestic goods with 20% tax.
*/
public class DomesticTaxCalculator implements TaxCalculator {
public static final double TAX_PERCENTAGE = 20;
@Override
public double calculate(double amount) {
return amount * TAX_PERCENTAGE / 100.0;
}
}
| 1,673
| 38.857143
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dirty-flag/src/test/java/org/dirty/flag/DirtyFlagTest.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 org.dirty.flag;
import com.iluwatar.dirtyflag.DataFetcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
class DirtyFlagTest {
@Test
void testIsDirty() {
var df = new DataFetcher();
var countries = df.fetch();
Assertions.assertFalse(countries.isEmpty());
}
@Test
void testIsNotDirty() {
var df = new DataFetcher();
df.fetch();
var countries = df.fetch();
Assertions.assertTrue(countries.isEmpty());
}
}
| 1,797
| 34.254902
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dirty-flag/src/test/java/org/dirty/flag/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 org.dirty.flag;
import com.iluwatar.dirtyflag.App;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Tests that Dirty-Flag example runs without errors.
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* 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,865
| 37.081633
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.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.dirtyflag;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* A mock database manager -- Fetches data from a raw file.
*
* @author swaisuan
*/
@Slf4j
public class DataFetcher {
private final String filename = "world.txt";
private long lastFetched;
public DataFetcher() {
this.lastFetched = -1;
}
private boolean isDirty(long fileLastModified) {
if (lastFetched != fileLastModified) {
lastFetched = fileLastModified;
return true;
}
return false;
}
/**
* Fetches data/content from raw file.
*
* @return List of strings
*/
public List<String> fetch() {
var classLoader = getClass().getClassLoader();
var file = new File(classLoader.getResource(filename).getFile());
if (isDirty(file.lastModified())) {
LOGGER.info(filename + " is dirty! Re-fetching file content...");
try (var br = new BufferedReader(new FileReader(file))) {
return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf));
} catch (IOException e) {
e.printStackTrace();
}
}
return List.of();
}
}
| 2,578
| 31.64557
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dirty-flag/src/main/java/com/iluwatar/dirtyflag/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.dirtyflag;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* This application demonstrates the <b>Dirty Flag</b> pattern. The dirty flag behavioral pattern
* allows you to avoid expensive operations that would just need to be done again anyway. This is a
* simple pattern that really just explains how to add a bool value to your class that you can set
* anytime a property changes. This will let your class know that any results it may have previously
* calculated will need to be calculated again when they’re requested. Once the results are
* re-calculated, then the bool value can be cleared.
*
* <p>There are some points that need to be considered before diving into using this pattern:-
* there are some things you’ll need to consider:- (1) Do you need it? This design pattern works
* well when the results to be calculated are difficult or resource intensive to compute. You want
* to save them. You also don’t want to be calculating them several times in a row when only the
* last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within
* the class itself whenever an important property changes. This property should affect the result
* of the calculated result and by changing the property, that makes the last result invalid. (3)
* When do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared
* whenever the result is calculated with up-to-date information but there are other times when you
* might want to clear the flag.
*
* <p>In this example, the {@link DataFetcher} holds the <i>dirty flag</i>. It fetches and
* re-fetches from <i>world.txt</i> when needed. {@link World} mainly serves the data to the
* front-end.
*/
@Slf4j
public class App {
/**
* Program execution point.
*/
public void run() {
final var executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
final World world = new World();
@Override
public void run() {
var countries = world.fetch();
LOGGER.info("Our world currently has the following countries:-");
countries.stream().map(country -> "\t" + country).forEach(LOGGER::info);
}
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
}
| 3,845
| 44.247059
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.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.dirtyflag;
import java.util.ArrayList;
import java.util.List;
/**
* A middle-layer app that calls/passes along data from the back-end.
*
* @author swaisuan
*/
public class World {
private List<String> countries;
private final DataFetcher df;
public World() {
this.countries = new ArrayList<>();
this.df = new DataFetcher();
}
/**
* Calls {@link DataFetcher} to fetch data from back-end.
*
* @return List of strings
*/
public List<String> fetch() {
var data = df.fetch();
countries = data.isEmpty() ? countries : data;
return countries;
}
}
| 1,900
| 32.946429
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.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.servicelocator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Date: 12/29/15 - 19:07 PM
*
* @author Jeroen Meulemeester
*/
class ServiceLocatorTest {
/**
* Verify if we just receive 'null' when requesting a non-existing service
*/
@Test
void testGetNonExistentService() {
assertNull(ServiceLocator.getService("fantastic/unicorn/service"));
assertNull(ServiceLocator.getService("another/fantastic/unicorn/service"));
}
/**
* Verify if we get the same cached instance when requesting the same service twice
*/
@Test
void testServiceCache() {
final var serviceNames = List.of("jndi/serviceA", "jndi/serviceB");
for (final var serviceName : serviceNames) {
final var service = ServiceLocator.getService(serviceName);
assertNotNull(service);
assertEquals(serviceName, service.getName());
assertTrue(service.getId() > 0); // The id is generated randomly, but the minimum value is '1'
assertSame(service, ServiceLocator.getService(serviceName));
}
}
}
| 2,657
| 37.521739
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/test/java/com/iluwatar/servicelocator/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.servicelocator;
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,582
| 37.609756
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/main/java/com/iluwatar/servicelocator/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.servicelocator;
/**
* The Service Locator pattern is a design pattern used in software development to encapsulate the
* processes involved in obtaining a service with a strong abstraction layer. This pattern uses a
* central registry known as the "service locator", which on request returns the information
* necessary to perform a certain task.
*
* <p>In this example we use the Service locator pattern to lookup JNDI-services and cache them for
* subsequent requests.
* <br>
*
* @author saifasif
*/
public class App {
public static final String JNDI_SERVICE_A = "jndi/serviceA";
public static final String JNDI_SERVICE_B = "jndi/serviceB";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_B);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
service = ServiceLocator.getService(JNDI_SERVICE_A);
service.execute();
}
}
| 2,416
| 39.283333
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/main/java/com/iluwatar/servicelocator/InitContext.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.servicelocator;
import lombok.extern.slf4j.Slf4j;
/**
* For JNDI lookup of services from the web.xml. Will match name of the service name that is being
* requested and return a newly created service object with the name
*
* @author saifasif
*/
@Slf4j
public class InitContext {
/**
* Perform the lookup based on the service name. The returned object will need to be casted into a
* {@link Service}
*
* @param serviceName a string
* @return an {@link Object}
*/
public Object lookup(String serviceName) {
if (serviceName.equals("jndi/serviceA")) {
LOGGER.info("Looking up service A and creating new service for A");
return new ServiceImpl("jndi/serviceA");
} else if (serviceName.equals("jndi/serviceB")) {
LOGGER.info("Looking up service B and creating new service for B");
return new ServiceImpl("jndi/serviceB");
} else {
return null;
}
}
}
| 2,226
| 38.070175
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceLocator.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.servicelocator;
/**
* The service locator module. Will fetch service from cache, otherwise creates a fresh service and
* update cache
*
* @author saifasif
*/
public final class ServiceLocator {
private static final ServiceCache serviceCache = new ServiceCache();
private ServiceLocator() {
}
/**
* Fetch the service with the name param from the cache first, if no service is found, lookup the
* service from the {@link InitContext} and then add the newly created service into the cache map
* for future requests.
*
* @param serviceJndiName a string
* @return {@link Service}
*/
public static Service getService(String serviceJndiName) {
var serviceObj = serviceCache.getService(serviceJndiName);
if (serviceObj != null) {
return serviceObj;
} else {
/*
* If we are unable to retrieve anything from cache, then lookup the service and add it in the
* cache map
*/
var ctx = new InitContext();
serviceObj = (Service) ctx.lookup(serviceJndiName);
if (serviceObj != null) { // Only cache a service if it actually exists
serviceCache.addService(serviceObj);
}
return serviceObj;
}
}
}
| 2,513
| 37.090909
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/main/java/com/iluwatar/servicelocator/ServiceImpl.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.servicelocator;
import lombok.extern.slf4j.Slf4j;
/**
* This is a single service implementation of a sample service. This is the actual service that will
* process the request. The reference for this service is to be looked upon in the JNDI server that
* can be set in the web.xml deployment descriptor
*
* @author saifasif
*/
@Slf4j
public class ServiceImpl implements Service {
private final String serviceName;
private final int id;
/**
* Constructor.
*/
public ServiceImpl(String serviceName) {
// set the service name
this.serviceName = serviceName;
// Generate a random id to this service object
this.id = (int) Math.floor(Math.random() * 1000) + 1;
}
@Override
public String getName() {
return serviceName;
}
@Override
public int getId() {
return id;
}
@Override
public void execute() {
LOGGER.info("Service {} is now executing with id {}", getName(), getId());
}
}
| 2,254
| 32.161765
| 140
|
java
|
java-design-patterns
|
java-design-patterns-master/service-locator/src/main/java/com/iluwatar/servicelocator/Service.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.servicelocator;
/**
* This is going to be the parent service interface which we will use to create our services. All
* services will have a <ul><li>service name</li> <li>unique id</li> <li>execution work
* flow</li></ul>
*
* @author saifasif
*/
public interface Service {
/*
* The human readable name of the service
*/
String getName();
/*
* Unique ID of the particular service
*/
int getId();
/*
* The workflow method that defines what this service does
*/
void execute();
}
| 1,821
| 34.72549
| 140
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.