|
1 | 1 | package com.baeldung.overridemethod.decorator; |
2 | 2 |
|
3 | 3 | import com.baeldung.overridemethod.Calculator; |
4 | | -import org.slf4j.Logger; |
5 | | -import org.slf4j.LoggerFactory; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
6 | 6 |
|
7 | | -public class LoggingCalculatorDecorator implements Calculator { |
8 | | - private static final Logger log = LoggerFactory.getLogger(LoggingCalculatorDecorator.class); |
| 7 | +public class MeteredCalculator implements Calculator { |
9 | 8 | private final Calculator wrappedCalculator; |
| 9 | + private final Map<String, Integer> methodCalls; |
10 | 10 |
|
11 | | - public LoggingCalculatorDecorator(Calculator calculator) { |
| 11 | + public MeteredCalculator(Calculator calculator) { |
12 | 12 | this.wrappedCalculator = calculator; |
| 13 | + this.methodCalls = new HashMap<>(); |
| 14 | + // Initialize counts for clarity |
| 15 | + methodCalls.put("add", 0); |
| 16 | + methodCalls.put("subtract", 0); |
13 | 17 | } |
14 | 18 |
|
15 | 19 | @Override |
16 | 20 | public int add(int a, int b) { |
17 | | - log.debug("DECORATOR LOG: Entering add({}, {})", a, b); |
18 | | - int result = wrappedCalculator.add(a, b); // Delegation |
19 | | - log.debug("DECORATOR LOG: Exiting add. Result: {}", result); |
20 | | - return result; |
| 21 | + // Track the call count |
| 22 | + methodCalls.merge("add", 1, Integer::sum); |
| 23 | + return wrappedCalculator.add(a, b); // Delegation |
21 | 24 | } |
22 | 25 |
|
23 | 26 | @Override |
24 | 27 | public int subtract(int a, int b) { |
25 | | - log.debug("DECORATOR LOG: Entering subtract({}, {})", a, b); |
26 | | - int result = wrappedCalculator.subtract(a, b); // Delegation |
27 | | - log.debug("DECORATOR LOG: Exiting subtract. Result: {}", result); |
28 | | - return result; |
| 28 | + // Track the call count |
| 29 | + methodCalls.merge("subtract", 1, Integer::sum); |
| 30 | + return wrappedCalculator.subtract(a, b); // Delegation |
| 31 | + } |
| 32 | + |
| 33 | + // Public method to expose the call counts for testing |
| 34 | + public int getCallCount(String methodName) { |
| 35 | + return methodCalls.getOrDefault(methodName, 0); |
29 | 36 | } |
30 | 37 | } |
0 commit comments