-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlyweightTest.java
More file actions
114 lines (108 loc) · 2.73 KB
/
FlyweightTest.java
File metadata and controls
114 lines (108 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package tests.structural;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import patterns.structural.flyweight.OrbiterFlyweight;
import space.Planet;
/**
* FLYWEIGHT PATTERN
*
* <p>Purpose: Minimizes memory usage by sharing a common state between multiple objects instead of
* duplicating data.
*
* <p>When to use:
*
* <ul>
* <li>When you need to support a large number of similar objects
* <li>When memory usage is a concern
* <li>When object state can be divided into intrinsic and extrinsic parts
* </ul>
*
* <p>Common Pitfalls:
*
* <ul>
* <li>Premature optimization
* <li>Not properly separating intrinsic and extrinsic state
* </ul>
*/
public class FlyweightTest {
/**
* When exploring space, we must be very careful with our resources. However, space is the great
* unknown, so we don't exactly know what to expect. We need to be able to adapt to potentially
* repeating situations and create orbiters on demand.
*
* <p>Use the flyweight pattern to create and store orbiters for various missions.
*
* @param planet to orbit
*/
@ParameterizedTest
@MethodSource("space.Planet#values")
void example(Planet planet) {
missionBacklog().forEach(mission -> OrbiterFlyweight.getOrCreate(mission).doOrbit(planet));
assertThat(OrbiterFlyweight.countOrbiters()).isEqualTo(6);
}
@Test
@Disabled
void todo() {
/*
* todo:
* create a new Flyweight class that creates 3 types of DedicatedOrbiters: pole, orbit, other
* */
}
private List<String> missionBacklog() {
return List.of(
"equator",
"moon",
"northPole",
"highOrbit",
"southPole",
"lowOrbit",
"highOrbit",
"equator",
"moon",
"northPole",
"southPole",
"lowOrbit",
"northPole",
"highOrbit",
"lowOrbit",
"moon",
"southPole",
"equator",
"southPole",
"lowOrbit",
"moon",
"northPole",
"highOrbit",
"equator",
"moon",
"equator",
"southPole",
"lowOrbit",
"highOrbit",
"northPole",
"lowOrbit",
"moon",
"northPole",
"southPole",
"equator",
"highOrbit",
"equator",
"northPole",
"highOrbit",
"southPole",
"lowOrbit",
"moon",
"moon",
"southPole",
"equator",
"highOrbit",
"northPole",
"lowOrbit"
// ... 1000s more
);
}
}