Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions factory/src/main/java/com/iluwatar/factory/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public class App {
/** Program main entry point. */
public static void main(String[] args) {
LOGGER.info("The alchemist begins his work.");
var coin1 = CoinFactory.getCoin(CoinType.COPPER);
var coin2 = CoinFactory.getCoin(CoinType.GOLD);
var coin1 = CoinType.COPPER.getInstance();
var coin2 = CoinType.GOLD.getInstance();
LOGGER.info(coin1.getDescription());
LOGGER.info(coin2.getDescription());
}
Expand Down
12 changes: 12 additions & 0 deletions factory/src/main/java/com/iluwatar/factory/CoinType.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
package com.iluwatar.factory;

import java.util.function.Supplier;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

Expand All @@ -36,4 +37,15 @@ public enum CoinType {
GOLD(GoldCoin::new);

private final Supplier<Coin> constructor;

@Getter(AccessLevel.NONE)
private Coin instance;

/** Returns singleton instance of this coin type. */
public Coin getInstance() {
if (instance == null) {
instance = constructor.get();
}
return instance;
}
Comment on lines +45 to +50

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getInstance() implements lazy initialization without synchronization, which is not thread-safe. In multi-threaded scenarios, two threads could observe instance == null and both create a Coin, potentially leaking one and returning a non-singleton. Consider a thread-safe lazy initialization strategy (e.g., double-checked locking with a volatile field, or initialize at enum construction).

}
14 changes: 13 additions & 1 deletion factory/src/test/java/com/iluwatar/factory/CoinFactoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,21 @@

class CoinFactoryTest {

@Test
void shouldReturnCopperCoinInstance() {
final var copperCoin = CoinType.COPPER.getInstance();
assertTrue(copperCoin instanceof CopperCoin);
}

@Test
void shouldReturnGoldCoinInstance() {
final var goldCoin = CoinFactory.getCoin(CoinType.GOLD);
final var goldCoin = CoinType.GOLD.getInstance();
assertTrue(goldCoin instanceof GoldCoin);
}

@Test
void shouldReturnSameInstanceEachTime() {
assertSame(CoinType.GOLD.getInstance(), CoinType.GOLD.getInstance());
assertSame(CoinType.COPPER.getInstance(), CoinType.COPPER.getInstance());
}
}
Loading