Last active
August 29, 2015 14:20
-
-
Save nelanka/ed0ac2cb7dad2a48b073 to your computer and use it in GitHub Desktop.
Proxy a cache that only uses String key and values
This file contains hidden or 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.concurrent.ConcurrentHashMap | |
trait StringDeserializer[T] { | |
def deserialize(s: String): T | |
} | |
trait StringSerializable[T] { | |
def serialize: String | |
} | |
class CacheProxy[K <: StringSerializable[K], V <: StringSerializable[V]] | |
(cache: ConcurrentHashMap[String, String])(implicit d: StringDeserializer[V]) { | |
def put(key: K, value: V) = cache.put(key.serialize, value.serialize) | |
def get(key: K): Option[V] = Option(cache.get(key.serialize)).map(d.deserialize) | |
} | |
case class Name(firstName: String, lastName: String) extends StringSerializable[Name] { | |
override def serialize: String = s"$firstName${NameDeserializer.delimiter}$lastName" | |
} | |
case class ContactInfo(phoneNumber: String, email: String) extends StringSerializable[ContactInfo] { | |
override def serialize: String = s"$phoneNumber${ContactInfoDeserializer.delimiter}$email" | |
} | |
implicit object NameDeserializer extends StringDeserializer[Name] { | |
val delimiter = '#' | |
override def deserialize(s: String): Name = { | |
val Array(firstName, lastName) = s.split(delimiter) | |
Name(firstName, lastName) | |
} | |
} | |
implicit object ContactInfoDeserializer extends StringDeserializer[ContactInfo] { | |
val delimiter = '#' | |
override def deserialize(s: String): ContactInfo = { | |
val Array(phoneNumber, email) = s.split(delimiter) | |
ContactInfo(phoneNumber, email) | |
} | |
} | |
val cache = new ConcurrentHashMap[String, String]() | |
val proxy = new CacheProxy[Name, ContactInfo](cache) | |
proxy.put(Name("James", "Kirk"), ContactInfo("917-123-4567", "[email protected]")) | |
println(proxy.get(Name("James", "Kirk"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment