我已经基于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都返回一个新的缓存)
答案 0 :(得分:0)
您可以限制对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 { ... }
}