Created
December 27, 2017 17:37
-
-
Save proshin-roman/71bc8f9484c73b3c258688a35bcae48b to your computer and use it in GitHub Desktop.
Yandex test program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Map; | |
import java.util.concurrent.ConcurrentHashMap; | |
import javax.annotation.Nonnull; | |
public class Main { | |
public static void main(String[] args) { | |
CacheableDigest digest = | |
new CacheableDigest( | |
new DigestImpl()); | |
// will print "The real method has been called" | |
byte[] input = { 1 }; | |
System.out.println("Case #1"); | |
digest.doDigest(input); | |
// will NOT print message as cache is used | |
System.out.println("Case #2"); | |
digest.doDigest(input); | |
// will print "The real method has been called" again, as Array's hashCode method is inherited from Object that | |
// uses | |
System.out.println("Case #3"); | |
digest.doDigest(new byte[] { 1 }); | |
} | |
public interface Digest { | |
@Nonnull | |
byte[] doDigest(@Nonnull byte[] input); | |
} | |
public static class DigestImpl implements Digest { | |
@Nonnull | |
@Override | |
public byte[] doDigest(@Nonnull byte[] input) { | |
// this method does the real job and it's a replacement for abstract doDigest method from the original code | |
System.out.println("The real method has been called"); | |
return input; | |
} | |
} | |
public static class CacheableDigest implements Digest { | |
private final Digest orig; | |
private final Map<byte[], byte[]> cache; | |
public CacheableDigest(@Nonnull Digest orig) { | |
this.orig = orig; | |
this.cache = new ConcurrentHashMap<>(); | |
} | |
@Nonnull | |
@Override | |
public byte[] doDigest(@Nonnull byte[] input) { | |
return cache.computeIfAbsent(input, orig::doDigest); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment