Created
March 23, 2023 10:32
-
-
Save jakzal/f114d5bb4a2126870406b755723c8fae to your computer and use it in GitHub Desktop.
Singleton Supplier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kaffeinelabs.function; | |
import java.util.function.Supplier; | |
public class Singleton<T> implements Supplier<T> { | |
private final Supplier<? extends T> factory; | |
private T instance = null; | |
private Singleton(final Supplier<? extends T> factory) { | |
this.factory = factory; | |
} | |
public static <T> Supplier<T> of(final Supplier<? extends T> factory) { | |
return new Singleton<>(factory); | |
} | |
@Override | |
public T get() { | |
if (this.instance == null) { | |
this.instance = this.factory.get(); | |
} | |
return this.instance; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kaffeinelabs.function; | |
import org.junit.jupiter.api.Test; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.Supplier; | |
import static org.junit.jupiter.api.Assertions.assertEquals; | |
public class SingletonTest { | |
final AtomicInteger instanceCount = new AtomicInteger(1); | |
@Test | |
void itCreatesAnInstanceOfTheObject() { | |
final Supplier<TestService> singleton = Singleton.of(() -> new TestService(instanceCount.getAndIncrement())); | |
final TestService service = singleton.get(); | |
assertEquals(new TestService(1), service); | |
} | |
@Test | |
void itCreatesASingleInstanceOfTheObject() { | |
final Supplier<TestService> singleton = Singleton.of(() -> new TestService(instanceCount.getAndIncrement())); | |
final TestService firstService = singleton.get(); | |
final TestService secondService = singleton.get(); | |
assertEquals(firstService, secondService); | |
} | |
record TestService(int number) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment