【问题标题】:Global immutable cache instance scala全局不可变缓存实例scala
【发布时间】:2017-01-14 22:05:43
【问题描述】:

我已经基于twitterStorehaus 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"))

我想在我的应用程序中保留此缓存的全局实例。我该怎么做(如何在应用程序中全局保存此缓存的单个实例?,每次放置都返回一个新缓存)

【问题讨论】:

    标签: scala caching functional-programming immutability higher-order-functions


    【解决方案1】:

    您可以限制对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 { ... }
    }
    

    【讨论】:

    • 问题不在于访问缓存,每个'put'都返回一个新的SenzCache,我该如何在应用程序中处理这个问题,我可以使用var cache = SenzCache.empty[String, String]而不是val,但是有没有其他方法.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2011-04-08
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多