Skip to content

Commit

Permalink
ffdb-005: add synchronized factory for DB
Browse files Browse the repository at this point in the history
  • Loading branch information
godcrampy committed Dec 28, 2023
1 parent 0aa996b commit 954ecaf
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/main/java/com/sahilbondre/firefly/FireflyDB.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package com.sahilbondre.firefly;

import java.util.HashMap;
import java.util.Map;

public class FireflyDB {
private static final Map<String, FireflyDB> 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;
}
}
53 changes: 53 additions & 0 deletions src/test/java/com/sahilbondre/firefly/FireflyDBTest.java
Original file line number Diff line number Diff line change
@@ -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()));
}
}

0 comments on commit 954ecaf

Please sign in to comment.