Skip to content

Commit 7baa063

Browse files
authored
Include static factory method in design patterns (#49)
1 parent e58681a commit 7baa063

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package pl.mperor.lab.java.design.pattern.creational.factory.stat.method;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
class Category {
7+
private static final Map<String, Category> CACHE = new HashMap<>();
8+
9+
private final String name;
10+
11+
private Category(String name) {
12+
this.name = name;
13+
}
14+
15+
static Category of(String name) {
16+
return CACHE.computeIfAbsent(name.toLowerCase(), Category::new);
17+
}
18+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package pl.mperor.lab.java.design.pattern.creational.factory.stat.method;
2+
3+
import java.util.Map;
4+
5+
record Pair<L, R>(L left, R right) {
6+
7+
private static final Pair EMPTY = new Pair<>(null, null);
8+
9+
static <L, R> Pair<L, R> of(L left, R right) {
10+
return new Pair<>(left, right);
11+
}
12+
13+
static <L, R> Pair<L, R> empty() {
14+
return EMPTY;
15+
}
16+
17+
static <L, R> Pair<L, R> left(L left) {
18+
return of(left, null);
19+
}
20+
21+
static <L, R> Pair<L, R> right(R right) {
22+
return of(null, right);
23+
}
24+
25+
static <L, R> Pair<L, R> fromMapEntry(Map.Entry<L, R> mapEntry) {
26+
return of(mapEntry.getKey(), mapEntry.getValue());
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package pl.mperor.lab.java.design.pattern.creational.factory.stat.method;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.Map;
7+
8+
public class StaticFactoryMethodTest {
9+
10+
@Test
11+
public void testClearNaming() {
12+
Assertions.assertEquals(new Pair<>("one", "two"), Pair.of("one", "two"));
13+
14+
Assertions.assertNull(Pair.empty().left());
15+
Assertions.assertNull(Pair.empty().right());
16+
17+
var onlyLeft = Pair.left("Only left");
18+
Assertions.assertNotNull(onlyLeft.left());
19+
Assertions.assertNull(onlyLeft.right());
20+
}
21+
22+
@Test
23+
public void testTypeConversion() {
24+
var entry = Map.entry(1, 2);
25+
var pair = Pair.fromMapEntry(entry);
26+
Assertions.assertEquals(pair.left(), entry.getKey());
27+
Assertions.assertEquals(pair.right(), entry.getValue());
28+
}
29+
30+
@Test
31+
public void testOptimizedObjectReuseAkaCaching() {
32+
Assertions.assertSame(Pair.empty(), Pair.empty());
33+
Assertions.assertSame(Category.of("Knowledge"), Category.of("Knowledge"));
34+
}
35+
}

0 commit comments

Comments
 (0)