Skip to content

Commit 99ef816

Browse files
committed
Added CacheAwareFactorialDecorator
1 parent 39ff39b commit 99ef816

File tree

4 files changed

+42
-0
lines changed

4 files changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package cz.muni.fi.pv243.lesson02.factorial;
2+
3+
import java.math.BigInteger;
4+
5+
import javax.decorator.Decorator;
6+
import javax.decorator.Delegate;
7+
import javax.enterprise.inject.Any;
8+
import javax.inject.Inject;
9+
10+
/**
11+
* Decorator that checks the {@link FactorialCache} before initiating computation. If the result is found in cache, it is
12+
* returned.
13+
*
14+
* @author Jozef Hartinger
15+
*
16+
*/
17+
@Decorator
18+
public class CacheAwareFactorialDecorator implements Factorial {
19+
20+
@Inject
21+
@Delegate
22+
@Any
23+
private Factorial delegate;
24+
25+
@Inject
26+
private FactorialCache cache;
27+
28+
@Override
29+
public BigInteger compute(long number) {
30+
BigInteger result = cache.get(number);
31+
if (result == null) {
32+
result = delegate.compute(number);
33+
}
34+
return result;
35+
}
36+
}

lesson02-cdi/src/main/java/cz/muni/fi/pv243/lesson02/factorial/FactorialCache.java

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import javax.ejb.LockType;
99
import javax.ejb.Singleton;
1010
import javax.enterprise.event.Observes;
11+
import javax.inject.Named;
1112

1213
import cz.muni.fi.pv243.lesson02.factorial.util.FactorialComputationFinished;
1314

@@ -19,6 +20,7 @@
1920
*
2021
*/
2122
@Singleton
23+
@Named
2224
public class FactorialCache {
2325
private final Map<Long, BigInteger> cachedResults = new HashMap<Long, BigInteger>();
2426

lesson02-cdi/src/main/webapp/WEB-INF/beans.xml

+3
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,7 @@
66
xsi:schemaLocation="
77
http://java.sun.com/xml/ns/javaee
88
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
9+
<decorators>
10+
<class>cz.muni.fi.pv243.lesson02.factorial.CacheAwareFactorialDecorator</class>
11+
</decorators>
912
</beans>

lesson02-cdi/src/main/webapp/factorial.xhtml

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
</h:inputText>
1313
<h:commandButton value="Compute" />
1414
<h:commandButton immediate="true" value="Reset" />
15+
<h:commandButton immediate="true" value="Clear cache" action="#{factorialCache.clear}" />
1516
<br />
1617
<br />
1718
<h:messages />

0 commit comments

Comments
 (0)