X Tutup
Skip to content

Commit b73ef6e

Browse files
Sia Wai SuanSia Wai Suan
authored andcommitted
Dirty Flag pattern iluwatar#560
1 parent e7b119c commit b73ef6e

File tree

8 files changed

+340
-1
lines changed

8 files changed

+340
-1
lines changed

dirty-flag/pom.xml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?xml version="1.0"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>com.iluwatar</groupId>
7+
<artifactId>java-design-patterns</artifactId>
8+
<version>1.19.0-SNAPSHOT</version>
9+
</parent>
10+
<groupId>com.iluwatar</groupId>
11+
<artifactId>dirty-flag</artifactId>
12+
<version>1.19.0-SNAPSHOT</version>
13+
<name>dirty-flag</name>
14+
<url>http://maven.apache.org</url>
15+
<properties>
16+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
17+
</properties>
18+
<dependencies>
19+
<dependency>
20+
<groupId>junit</groupId>
21+
<artifactId>junit</artifactId>
22+
<version>3.8.1</version>
23+
<scope>test</scope>
24+
</dependency>
25+
</dependencies>
26+
</project>
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
* <p>
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
* <p>
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
* <p>
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.dirtyflag;
24+
25+
import java.util.List;
26+
import java.util.concurrent.Executors;
27+
import java.util.concurrent.ScheduledExecutorService;
28+
import java.util.concurrent.TimeUnit;
29+
30+
import org.slf4j.Logger;
31+
import org.slf4j.LoggerFactory;
32+
33+
/**
34+
*
35+
* This application demonstrates the <b>Dirty Flag</b> pattern. The dirty flag behavioral pattern allows you to avoid
36+
* expensive operations that would just need to be done again anyway. This is a simple pattern that really just explains
37+
* how to add a bool value to your class that you can set anytime a property changes. This will let your class know that
38+
* any results it may have previously calculated will need to be calculated again when they’re requested. Once the
39+
* results are re-calculated, then the bool value can be cleared.
40+
*
41+
* There are some points that need to be considered before diving into using this pattern:- there are some things you’ll
42+
* need to consider:- (1) Do you need it? This design pattern works well when the results to be calculated are difficult
43+
* or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in
44+
* a row when only the last one counts. (2) When do you set the dirty flag? Make sure that you set the dirty flag within
45+
* the class itself whenever an important property changes. This property should affect the result of the calculated
46+
* result and by changing the property, that makes the last result invalid. (3) When do you clear the dirty flag? It
47+
* might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date
48+
* information but there are other times when you might want to clear the flag.
49+
*
50+
* In this example, the {@link DataFetcher} holds the <i>dirty flag</i>. It fetches and re-fetches from <i>world.txt</i>
51+
* when needed. {@link World} mainly serves the data to the front-end.
52+
*/
53+
public class App {
54+
55+
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
56+
57+
/**
58+
* Program execution point
59+
*/
60+
public void run() {
61+
62+
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
63+
executorService.scheduleAtFixedRate(new Runnable() {
64+
@Override
65+
public void run() {
66+
World world = World.getInstance();
67+
List<String> countries = world.fetch();
68+
System.out.println("Our world currently has the following countries:-");
69+
for (String country : countries) {
70+
System.out.println("\t" + country);
71+
}
72+
}
73+
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
74+
}
75+
76+
/**
77+
* Program entry point
78+
*
79+
* @param args
80+
* command line args
81+
*/
82+
public static void main(String[] args) {
83+
App app = new App();
84+
85+
app.run();
86+
}
87+
88+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.iluwatar.dirtyflag;
2+
3+
import java.io.BufferedReader;
4+
import java.io.File;
5+
import java.io.FileReader;
6+
import java.io.IOException;
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
10+
/**
11+
* A mock database manager -- Fetches data from a raw file.
12+
*
13+
* @author swaisuan
14+
*
15+
*/
16+
public class DataFetcher {
17+
18+
private static DataFetcher df;
19+
private final String filename = "world.txt";
20+
private long lastFetched = -1;
21+
22+
private DataFetcher() {
23+
}
24+
25+
/**
26+
* Init.
27+
*
28+
* @return DataFetcher instance
29+
*/
30+
public static DataFetcher getInstance() {
31+
if (df == null) {
32+
df = new DataFetcher();
33+
}
34+
return df;
35+
}
36+
37+
private boolean isDirty(long fileLastModified) {
38+
if (lastFetched != fileLastModified) {
39+
lastFetched = fileLastModified;
40+
return true;
41+
}
42+
return false;
43+
}
44+
45+
/**
46+
* Fetches data/content from raw file.
47+
*
48+
* @return List of strings
49+
*/
50+
public List<String> fetch() {
51+
ClassLoader classLoader = getClass().getClassLoader();
52+
File file = new File(classLoader.getResource(filename).getFile());
53+
54+
if (isDirty(file.lastModified())) {
55+
System.out.println(filename + " is dirty! Re-fetching file content...");
56+
57+
List<String> data = new ArrayList<String>();
58+
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
59+
String line;
60+
while ((line = br.readLine()) != null) {
61+
data.add(line);
62+
}
63+
} catch (IOException e) {
64+
e.printStackTrace();
65+
}
66+
return data;
67+
}
68+
69+
return null;
70+
}
71+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.iluwatar.dirtyflag;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
*
8+
* A middle-layer app that calls/passes along data from the back-end.
9+
*
10+
* @author swaisuan
11+
*
12+
*/
13+
public class World {
14+
15+
private static World world;
16+
private static List<String> countries = new ArrayList<String>();
17+
18+
private World() {
19+
}
20+
21+
/**
22+
* Init.
23+
*
24+
* @return World instance
25+
*/
26+
public static World getInstance() {
27+
if (world == null) {
28+
world = new World();
29+
}
30+
return world;
31+
}
32+
33+
/**
34+
*
35+
* Calls {@link DataFetcher} to fetch data from back-end.
36+
*
37+
* @return List of strings
38+
*/
39+
public List<String> fetch() {
40+
DataFetcher df = DataFetcher.getInstance();
41+
List<String> data = df.fetch();
42+
43+
countries = data == null ? countries : data;
44+
45+
return countries;
46+
}
47+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
UNITED_KINGDOM
2+
MALAYSIA
3+
UNITED_STATES
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package org.dirty.flag;
24+
25+
import java.io.IOException;
26+
27+
import org.junit.Test;
28+
29+
import com.iluwatar.dirtyflag.App;
30+
31+
/**
32+
* Tests that Dirty-Flag example runs without errors.
33+
*/
34+
public class AppTest {
35+
@Test
36+
public void test() throws IOException {
37+
String[] args = {};
38+
App.main(args);
39+
}
40+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package org.dirty.flag;
24+
25+
import static org.junit.Assert.assertTrue;
26+
27+
import java.lang.reflect.Field;
28+
import java.util.List;
29+
30+
import org.junit.Before;
31+
import org.junit.Test;
32+
33+
import com.iluwatar.dirtyflag.DataFetcher;
34+
35+
/**
36+
*
37+
* Application test
38+
*
39+
*/
40+
public class DirtyFlagTest {
41+
42+
@Before
43+
public void reset() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
44+
Field instance = DataFetcher.class.getDeclaredField("df");
45+
instance.setAccessible(true);
46+
instance.set(null, null);
47+
}
48+
49+
@Test
50+
public void testIsDirty() {
51+
DataFetcher df = DataFetcher.getInstance();
52+
List<String> countries = df.fetch();
53+
assertTrue(!countries.isEmpty());
54+
}
55+
56+
@Test
57+
public void testIsNotDirty() {
58+
DataFetcher df = DataFetcher.getInstance();
59+
df.fetch();
60+
List<String> countries = df.fetch();
61+
assertTrue(countries == null);
62+
}
63+
}

pom.xml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,8 @@
154154
<module>eip-splitter</module>
155155
<module>eip-aggregator</module>
156156
<module>retry</module>
157-
</modules>
157+
<module>dirty-flag</module>
158+
</modules>
158159

159160
<repositories>
160161
<repository>

0 commit comments

Comments
 (0)
X Tutup