我有一个简单的应用程序,它接受一个字符串并返回字符串中唯一字符的数量。预计一个字符串可能会多次传递给该方法。该方法应该缓存结果,以便在给该方法之前遇到的字符串时,它会检索存储的结果。
出于学习目的,我需要使用装饰器模式来实现缓存。我从网上学到的:
public interface CharCount {
Map<String, Long> charCount(String input);
}
Run Code Online (Sandbox Code Playgroud)
public class CharCountImplement {
Map<String, Long> charCount(String input) {
return Arrays.stream(input.split(""))
.collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
}
}
Run Code Online (Sandbox Code Playgroud)
public abstract class Decorator implements CharCount {
private CharCount charCount;
@Override
public Map<String, Long> charCount(String input) {
return charCount.charCount(input);
}
}
Run Code Online (Sandbox Code Playgroud)
public class CachedDecorator extends Decorator {
// decorator must contain something else
public Map<String, Long> charCount(String input) {
// some decoration code - no problem with …Run Code Online (Sandbox Code Playgroud)