Skip to content

Commit ca14e8d

Browse files
committed
Add proper tests for flyweight pattern
1 parent 3dc370e commit ca14e8d

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

flyweight/src/main/java/com/iluwatar/flyweight/AlchemistShop.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.iluwatar.flyweight;
22

33
import java.util.ArrayList;
4+
import java.util.Collections;
45
import java.util.List;
56

67
/**
@@ -39,6 +40,24 @@ private void fillShelves() {
3940
bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
4041
}
4142

43+
/**
44+
* Get a read-only list of all the items on the top shelf
45+
*
46+
* @return The top shelf potions
47+
*/
48+
public final List<Potion> getTopShelf() {
49+
return Collections.unmodifiableList(this.topShelf);
50+
}
51+
52+
/**
53+
* Get a read-only list of all the items on the bottom shelf
54+
*
55+
* @return The bottom shelf potions
56+
*/
57+
public final List<Potion> getBottomShelf() {
58+
return Collections.unmodifiableList(this.bottomShelf);
59+
}
60+
4261
public void enumerate() {
4362

4463
System.out.println("Enumerating top shelf potions\n");
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.iluwatar.flyweight;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
import static org.junit.Assert.assertEquals;
9+
import static org.junit.Assert.assertNotNull;
10+
11+
/**
12+
* Date: 12/12/15 - 10:54 PM
13+
*
14+
* @author Jeroen Meulemeester
15+
*/
16+
public class AlchemistShopTest {
17+
18+
@Test
19+
public void testShop() throws Exception {
20+
final AlchemistShop shop = new AlchemistShop();
21+
22+
final List<Potion> bottomShelf = shop.getBottomShelf();
23+
assertNotNull(bottomShelf);
24+
assertEquals(5, bottomShelf.size());
25+
26+
final List<Potion> topShelf = shop.getTopShelf();
27+
assertNotNull(topShelf);
28+
assertEquals(8, topShelf.size());
29+
30+
final List<Potion> allPotions = new ArrayList<>();
31+
allPotions.addAll(topShelf);
32+
allPotions.addAll(bottomShelf);
33+
34+
// There are 13 potion instances, but only 5 unique instance types
35+
assertEquals(13, allPotions.size());
36+
assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count());
37+
38+
}
39+
40+
}

0 commit comments

Comments
 (0)