Commit 9f8f8d9b authored by platanus's avatar platanus

feat(chap07): Make example code as proxy pattern

parent 1b3513a6
<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sp5</groupId>
<artifactId>sp5-chap07</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
package main.java.chap07;
public interface Calculator {
public long factorial(long num);
}
package main.java.chap07;
public class ExecutiveTimeCalculator implements Calculator {
private Calculator delegate;
public ExecutiveTimeCalculator(Calculator delegate) {
this.delegate = delegate;
}
@Override
public long factorial(long num) {
long start = System.nanoTime();
long result = delegate.factorial(num);
long end = System.nanoTime();
System.out.printf("%s.factorial(%d) runtime = %d\n",
delegate.getClass().getSimpleName(),
num,
(end - start));
return result;
}
}
package main.java.chap07;
public class ImplementCalculator implements Calculator {
@Override
public long factorial(long num) {
long result = 1;
for (long i = 1; i <= num; i++) {
result *= i;
}
return result;
}
}
package main.java.chap07;
public class MainProxy {
public static void main(String[] args) {
ExecutiveTimeCalculator timeToCalculator1 =
new ExecutiveTimeCalculator(new ImplementCalculator());
System.out.println(timeToCalculator1.factorial(20));
ExecutiveTimeCalculator timeToCalculator2 =
new ExecutiveTimeCalculator(new ImplementCalculator());
System.out.println(timeToCalculator2.factorial(3));
}
}
package main.java.chap07;
public class ReCalculator implements Calculator {
@Override
public long factorial(long num) {
if (num == 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment