Skip to content

Commit eddfe76

Browse files
authored
Merge pull request iluwatar#717 from waisuan/master
Dirty Flag pattern iluwatar#560
2 parents 4ac6f90 + a386d42 commit eddfe76

File tree

11 files changed

+377
-1
lines changed

11 files changed

+377
-1
lines changed

dirty-flag/README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
layout: pattern
3+
title: Dirty Flag
4+
folder: dirty-flag
5+
permalink: /patterns/dirty-flag/
6+
categories: Other
7+
tags:
8+
- Java
9+
- Difficulty-Easy
10+
- Performance
11+
---
12+
13+
## Intent
14+
To avoid expensive re-acquisition of resources. The resources retain their identity, are kept in some
15+
fast-access storage, and are re-used to avoid having to acquire them again.
16+
17+
![alt text](./etc/dirty-flag.png "Dirty Flag")
18+
19+
## Applicability
20+
Use the Dirty Flag pattern when
21+
22+
* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead.
23+
24+
## Credits
25+
26+
* [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/)

dirty-flag/etc/dirty-flag.png

8.98 KB
Loading

dirty-flag/etc/dirty-flag.ucls

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<class-diagram version="1.2.2" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
3+
realizations="true" associations="true" dependencies="false" nesting-relationships="true" router="FAN">
4+
<class id="1" language="java" name="com.iluwatar.dirtyflag.App" project="dirty-flag"
5+
file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/App.java" binary="false" corner="BOTTOM_RIGHT">
6+
<position height="-1" width="-1" x="266" y="188"/>
7+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
8+
sort-features="false" accessors="true" visibility="true">
9+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
10+
<operations public="true" package="true" protected="true" private="true" static="true"/>
11+
</display>
12+
</class>
13+
<class id="2" language="java" name="com.iluwatar.dirtyflag.DataFetcher" project="dirty-flag"
14+
file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java" binary="false" corner="BOTTOM_RIGHT">
15+
<position height="153" width="125" x="66" y="291"/>
16+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
17+
sort-features="false" accessors="true" visibility="true">
18+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
19+
<operations public="true" package="true" protected="true" private="true" static="true"/>
20+
</display>
21+
</class>
22+
<class id="3" language="java" name="com.iluwatar.dirtyflag.World" project="dirty-flag"
23+
file="/dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java" binary="false" corner="BOTTOM_RIGHT">
24+
<position height="-1" width="-1" x="379" y="366"/>
25+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
26+
sort-features="false" accessors="true" visibility="true">
27+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
28+
<operations public="true" package="true" protected="true" private="true" static="true"/>
29+
</display>
30+
</class>
31+
<association id="4">
32+
<end type="SOURCE" refId="3" navigable="false">
33+
<attribute id="5" name="df"/>
34+
<multiplicity id="6" minimum="0" maximum="1"/>
35+
</end>
36+
<end type="TARGET" refId="2" navigable="true"/>
37+
<display labels="true" multiplicity="true"/>
38+
</association>
39+
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
40+
sort-features="false" accessors="true" visibility="true">
41+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
42+
<operations public="true" package="true" protected="true" private="true" static="true"/>
43+
</classifier-display>
44+
<association-display labels="true" multiplicity="true"/>
45+
</class-diagram>

dirty-flag/pom.xml

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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.20.0-SNAPSHOT</version>
9+
</parent>
10+
<groupId>com.iluwatar</groupId>
11+
<artifactId>dirty-flag</artifactId>
12+
<version>1.20.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>org.junit.jupiter</groupId>
21+
<artifactId>junit-jupiter-api</artifactId>
22+
<scope>test</scope>
23+
</dependency>
24+
<dependency>
25+
<groupId>org.junit.jupiter</groupId>
26+
<artifactId>junit-jupiter-engine</artifactId>
27+
<scope>test</scope>
28+
</dependency>
29+
</dependencies>
30+
</project>
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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+
/**
31+
*
32+
* This application demonstrates the <b>Dirty Flag</b> pattern. The dirty flag behavioral pattern allows you to avoid
33+
* expensive operations that would just need to be done again anyway. This is a simple pattern that really just explains
34+
* how to add a bool value to your class that you can set anytime a property changes. This will let your class know that
35+
* any results it may have previously calculated will need to be calculated again when they’re requested. Once the
36+
* results are re-calculated, then the bool value can be cleared.
37+
*
38+
* There are some points that need to be considered before diving into using this pattern:- there are some things you’ll
39+
* need to consider:- (1) Do you need it? This design pattern works well when the results to be calculated are difficult
40+
* or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in
41+
* 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
42+
* the class itself whenever an important property changes. This property should affect the result of the calculated
43+
* result and by changing the property, that makes the last result invalid. (3) When do you clear the dirty flag? It
44+
* might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date
45+
* information but there are other times when you might want to clear the flag.
46+
*
47+
* In this example, the {@link DataFetcher} holds the <i>dirty flag</i>. It fetches and re-fetches from <i>world.txt</i>
48+
* when needed. {@link World} mainly serves the data to the front-end.
49+
*/
50+
public class App {
51+
/**
52+
* Program execution point
53+
*/
54+
public void run() {
55+
56+
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
57+
executorService.scheduleAtFixedRate(new Runnable() {
58+
@Override
59+
public void run() {
60+
World world = new World();
61+
List<String> countries = world.fetch();
62+
System.out.println("Our world currently has the following countries:-");
63+
for (String country : countries) {
64+
System.out.println("\t" + country);
65+
}
66+
}
67+
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.
68+
}
69+
70+
/**
71+
* Program entry point
72+
*
73+
* @param args
74+
* command line args
75+
*/
76+
public static void main(String[] args) {
77+
App app = new App();
78+
79+
app.run();
80+
}
81+
82+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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 final String filename = "world.txt";
19+
private long lastFetched;
20+
21+
public DataFetcher() {
22+
this.lastFetched = -1;
23+
}
24+
25+
private boolean isDirty(long fileLastModified) {
26+
if (lastFetched != fileLastModified) {
27+
lastFetched = fileLastModified;
28+
return true;
29+
}
30+
return false;
31+
}
32+
33+
/**
34+
* Fetches data/content from raw file.
35+
*
36+
* @return List of strings
37+
*/
38+
public List<String> fetch() {
39+
ClassLoader classLoader = getClass().getClassLoader();
40+
File file = new File(classLoader.getResource(filename).getFile());
41+
42+
if (isDirty(file.lastModified())) {
43+
System.out.println(filename + " is dirty! Re-fetching file content...");
44+
45+
List<String> data = new ArrayList<String>();
46+
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
47+
String line;
48+
while ((line = br.readLine()) != null) {
49+
data.add(line);
50+
}
51+
} catch (IOException e) {
52+
e.printStackTrace();
53+
}
54+
return data;
55+
}
56+
57+
return new ArrayList<String>();
58+
}
59+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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 List<String> countries;
16+
private DataFetcher df;
17+
18+
public World() {
19+
this.countries = new ArrayList<String>();
20+
this.df = new DataFetcher();
21+
}
22+
23+
/**
24+
*
25+
* Calls {@link DataFetcher} to fetch data from back-end.
26+
*
27+
* @return List of strings
28+
*/
29+
public List<String> fetch() {
30+
List<String> data = df.fetch();
31+
32+
countries = data.isEmpty() ? countries : data;
33+
34+
return countries;
35+
}
36+
}
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.jupiter.api.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: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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.jupiter.api.Assertions.assertTrue;
26+
27+
import java.util.List;
28+
29+
import org.junit.jupiter.api.Test;
30+
31+
import com.iluwatar.dirtyflag.DataFetcher;
32+
33+
/**
34+
*
35+
* Application test
36+
*
37+
*/
38+
public class DirtyFlagTest {
39+
40+
@Test
41+
public void testIsDirty() {
42+
DataFetcher df = new DataFetcher();
43+
List<String> countries = df.fetch();
44+
assertTrue(!countries.isEmpty());
45+
}
46+
47+
@Test
48+
public void testIsNotDirty() {
49+
DataFetcher df = new DataFetcher();
50+
df.fetch();
51+
List<String> countries = df.fetch();
52+
assertTrue(countries.isEmpty());
53+
}
54+
}

pom.xml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@
158158
<module>eip-splitter</module>
159159
<module>eip-aggregator</module>
160160
<module>retry</module>
161-
<module>trampoline</module>
161+
<module>dirty-flag</module>
162+
<module>trampoline</module>
162163
<module>serverless</module>
163164
</modules>
164165

0 commit comments

Comments
 (0)