diff --git a/src/main/java/com/sahilbondre/firefly/FireflyDB.java b/src/main/java/com/sahilbondre/firefly/FireflyDB.java index abbb517..b08c40f 100644 --- a/src/main/java/com/sahilbondre/firefly/FireflyDB.java +++ b/src/main/java/com/sahilbondre/firefly/FireflyDB.java @@ -1,5 +1,22 @@ package com.sahilbondre.firefly; +import java.util.HashMap; +import java.util.Map; + public class FireflyDB { + private static final Map instances = new HashMap<>(); + private final String folderPath; + + private FireflyDB(String folderPath) { + this.folderPath = folderPath; + } + + public static synchronized FireflyDB getInstance(String folderPath) { + instances.computeIfAbsent(folderPath, FireflyDB::new); + return instances.get(folderPath); + } + public String getFolderPath() { + return folderPath; + } } diff --git a/src/test/java/com/sahilbondre/firefly/FireflyDBTest.java b/src/test/java/com/sahilbondre/firefly/FireflyDBTest.java new file mode 100644 index 0000000..2449abc --- /dev/null +++ b/src/test/java/com/sahilbondre/firefly/FireflyDBTest.java @@ -0,0 +1,53 @@ +package com.sahilbondre.firefly; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import static org.junit.jupiter.api.Assertions.*; + +class FireflyDBTest { + + private static final String FOLDER_A = "/path/to/folderA"; + private static final String FOLDER_B = "/path/to/folderB"; + + @Test + void givenSameFolder_whenGetInstance_thenSameObjectReferenced() { + // Given + // Two instances with the same folder should reference the same object + + // When + FireflyDB dbA1 = FireflyDB.getInstance(FOLDER_A); + FireflyDB dbA2 = FireflyDB.getInstance(FOLDER_A); + + // Then + assertSame(dbA1, dbA2); + assertEquals(FOLDER_A, dbA1.getFolderPath()); + assertEquals(FOLDER_A, dbA1.getFolderPath()); + } + + @Test + void givenDifferentFolders_whenGetInstance_thenDifferentObjectsReferenced() { + // Given + // Two instances with different folders should reference different objects + + // When + FireflyDB dbA = FireflyDB.getInstance(FOLDER_A); + FireflyDB dbB = FireflyDB.getInstance(FOLDER_B); + + // Then + assertNotSame(dbA, dbB); + assertEquals(FOLDER_A, dbA.getFolderPath()); + assertEquals(FOLDER_B, dbB.getFolderPath()); + } + + @Test + void givenGetInstanceMethod_whenCheckSynchronizedModifier_thenTrue() throws NoSuchMethodException { + // Given + Method getInstanceMethod = FireflyDB.class.getDeclaredMethod("getInstance", String.class); + + // When/Then + assertTrue(Modifier.isSynchronized(getInstanceMethod.getModifiers())); + } +}