lundi 22 mars 2021

Having trouble implementing my first Decorator pattern

I have a simple app that takes a string and returns the number of unique characters in the string. It is expected that a string may be passed several times to the method. The method should cache the results, so that when the method is given a string previously encountered, it will retrieve the stored result.

For learning purposes I need to implement caching using decorator pattern. What I learned from the web:

  1. First I create an interface
public interface CharCount {
                Map<String, Long> charCount(String input);
        }
  1. It's simple implementation - without caching
public class CharCountImplement {

    Map<String, Long> charCount(String input) {
        return Arrays.stream(input.split(""))
                .collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
    }
}
  1. Decorator class
public abstract class Decorator implements CharCount {
    private CharCount charCount;

    @Override
    public Map<String, Long> charCount(String input) {
        return charCount.charCount(input);
    }
}
  1. Now I must create the concrete decorator, but I can't quite figure it out
public class CachedDecorator extends Decorator {

    // decorator must contain something else

    public Map<String, Long> charCount(String input) {
        // some decoration code - no problem with it
        return super.charCount(input);
    }

}

I don't quite catch the principle of this design pattern, and how to use it in my case. I have watched/read numerous tutorials for pizza and coffee decorators, did not help.

Aucun commentaire:

Enregistrer un commentaire