Skip to content

Instantly share code, notes, and snippets.

@jakzal
Created March 23, 2023 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakzal/f114d5bb4a2126870406b755723c8fae to your computer and use it in GitHub Desktop.
Save jakzal/f114d5bb4a2126870406b755723c8fae to your computer and use it in GitHub Desktop.
Singleton Supplier
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;
}
}
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