0

我怎样才能将以下内容转换为 scala.

public class JedisDB {
  private static final JedisPool jedisPool = new JedisPool(getJedisPoolConfig());


  public static JedisPoolConfig getJedisPool() {
      // ..
  }

  public int getTest123() {
         jedisPool.getResource();
         // code goes here
  }
}

我已经看到答案确实创建了一个类和一个伴随对象,但是有人可以向我解释我应该如何以及为什么要这样做吗?

我是否应该在伴随对象中创建我想要作为静态变量公开的内容,以及加载用于在类中初始化 jedisPool 的配置文件?

我可以选择在伴生对象中将 jedisPool 设为公开还是私有?

另外(不影响对我的问题的回答,但作为一个额外的好处),我在某处读过但没有完全理解这使得模式使测试变得困难,那么有解决方法吗?

4

2 回答 2

0
lazy val jedisPool : JedisPool = {
   val poolConfig = createPoolConfig(app)
   new JedisPool(poolConfig)
 }

获取资源

 val j = jedisPool.getResource()

确保在使用完资源后返回资源。

 jedisPool.returnResource(j)
于 2014-05-22T01:43:15.547 回答
0

基本上,静态方法是否会转到伴生对象或任何其他对象并没有关系。伴随对象与其他对象不同,因为它具有对其他对象没有的类/特征的访问权限。但这不是你的例子。

您的伴随对象样本:

// -- helpers to be able compile
class JedisPoolConfig { }
class JedisPool(p: JedisPoolConfig) {
  def getResource = 1
}
// --

// everythis that should be SINGLETON goes into object
object JedisDB {
  private lazy val jedisPool = new JedisPool(getJedisPool)
  def getJedisPool = new JedisPoolConfig()   // or any other implementation
  def otherStaticMethod = new JedisDB().anyVal // wow - got access to private val.
}

class JedisDB {
  import JedisDB._
  def  getTest123() = jedisPool.getResource


  private val anyVal = "SomeValue";

  // other methods 

}

// other - non companion object
object JedisDB2 {
  // def otherStaticMethod = new JedisDB().anyVal // no luck - no access
}
于 2014-05-22T09:48:00.723 回答