我已经实现了基于twitter Storehaus Cache的不可变缓存。
以下是代码
接口
trait Cache[K, V] {
def get(k: K): Option[V]
def put(kv: (K, V)): (Set[K], Cache[K, V])
def iterator: Iterator[(K, V)]
}实现
object SenzCache {
def empty[K, V]: SenzCache[K, V] = SenzCache[K, V](Map.empty[K, V])
def apply[K, V](m: Map[K, V]): SenzCache[K, V] = new SenzCache[K, V](m)
}
class SenzCache[K, V](m: Map[K, V]) extends Cache[K, V] {
override def get(k: K): Option[V] = {
m.get(k)
}
override def put(kv: (K, V)): (Set[K], Cache[K, V]) = {
(Set.empty[K], new SenzCache(m + kv))
}
override def iterator: Iterator[(K, V)] = m.iterator
override def toString: String = m.toString()
}我可以像下面这样使用这个缓存,
val c = SenzCache.empty[String, String]
val c1 = cache.put("era" -> "foo")._2
val c2 = c.put("ban" -> "bar")._2
println(c2.get("era"))我想在我的应用程序中保留这个缓存的全局实例。如何做到这一点(如何在应用程序中全局保留此缓存的单个实例?每次put都会返回一个新的缓存)
发布于 2016-09-07 17:45:18
您可以限制对Cache构造函数的访问,并提供如下示例所示的lazy val instance = new CacheImpl:
sealed trait Cache {
// your cache methods
}
object Cache {
private lazy val instance: Cache = new CacheImpl
def apply(...) = instance
private class CacheImpl(...) extends Cache { ... }
}https://stackoverflow.com/questions/39366105
复制相似问题