Skip to content

Commit

Permalink
Added CacheAwareFactorialDecorator
Browse files Browse the repository at this point in the history
  • Loading branch information
jharting committed Mar 15, 2012
1 parent 39ff39b commit 99ef816
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cz.muni.fi.pv243.lesson02.factorial;

import java.math.BigInteger;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.inject.Any;
import javax.inject.Inject;

/**
* Decorator that checks the {@link FactorialCache} before initiating computation. If the result is found in cache, it is
* returned.
*
* @author Jozef Hartinger
*
*/
@Decorator
public class CacheAwareFactorialDecorator implements Factorial {

@Inject
@Delegate
@Any
private Factorial delegate;

@Inject
private FactorialCache cache;

@Override
public BigInteger compute(long number) {
BigInteger result = cache.get(number);
if (result == null) {
result = delegate.compute(number);
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.inject.Named;

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

Expand All @@ -19,6 +20,7 @@
*
*/
@Singleton
@Named
public class FactorialCache {
private final Map<Long, BigInteger> cachedResults = new HashMap<Long, BigInteger>();

Expand Down
3 changes: 3 additions & 0 deletions lesson02-cdi/src/main/webapp/WEB-INF/beans.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<decorators>
<class>cz.muni.fi.pv243.lesson02.factorial.CacheAwareFactorialDecorator</class>
</decorators>
</beans>
1 change: 1 addition & 0 deletions lesson02-cdi/src/main/webapp/factorial.xhtml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</h:inputText>
<h:commandButton value="Compute" />
<h:commandButton immediate="true" value="Reset" />
<h:commandButton immediate="true" value="Clear cache" action="#{factorialCache.clear}" />
<br />
<br />
<h:messages />
Expand Down

0 comments on commit 99ef816

Please sign in to comment.