9

假设我们有一个具有“名称”属性的类:

class SuperFoo(var name: String) 

如果我想覆盖它,例如在调用周围添加一些锁定:

class SubFoo(n: String) extends SuperFoo(n) {
  val lock = new ReentrantLock
  override def name(): String =
    {
      lock.lock
      try {
        super.name
      } finally {
        lock.unlock
      }
    }
  override def name_=(arg: String): Unit = {
    lock.lock
    try {
      super.name = arg
    } finally {
      lock.unlock
    }
  }
}

以上会产生编译错误:

super may be not be used on variable name 

任何想法如何正确实现这一点?(即覆盖 getter 和 setter 以在它们周围添加锁定)。谢谢!

4

1 回答 1

6

这里需要直接引用超类的setter/getter。通常你应该写这样的东西:

class SubFoo(n: String) extends SuperFoo(n) {
  val lock = new ReentrantLock
  override def name(): String =
    {
      lock.lock
      try {
        super.name()
      } finally {
        lock.unlock
      }
    }
  override def name_=(arg: String): Unit = {
    lock.lock
    try {
      super.name_=(arg)
    } finally {
      lock.unlock
    }
  }
}

但是,如果 setter 编译没有任何问题,getter 则不会,因为编译器会将其视为super.name.apply()(字符串可以通过隐式转换获得此方法)。

我看到几个选项:

  1. 喜欢组合而不是继承(经典)。
  2. 更改变量名,使其私有并在超类中写入访问器(见下文)。
  3. 诉诸反射/手动名称 umangling voodoo。

我会选择选项 #1,但这里是选项 #2 的代码:

class SuperFoo( private var nameVar: String) {
  def name: String = nameVar
  def name_=(arg: String): Unit = nameVar = arg
}

class SubFoo(n: String) extends SuperFoo(n) {
  val lock = new ReentrantLock
  override def name(): String =
    {
      lock.lock
      try {
    super.name
      } finally {
        lock.unlock
      }
    }
  override def name_=(arg: String): Unit = {
    lock.lock
    try {
      super.name = arg
    } finally {
      lock.unlock
    }
  }
}

编辑:这是选项#1的可行实现:

trait Foo {
  def name: String
  def name_=(arg: String): Unit
}

class SimpleFoo( var name: String) extends Foo

class LockedFoo(foo: Foo) extends Foo {
  val lock = new ReentrantLock
  def name(): String =
    {
      lock.lock
      try {
        foo.name
      } finally {
        lock.unlock
      }
    }
  def name_=(arg: String): Unit = {
    lock.lock
    try {
      foo.name = arg
    } finally {
      lock.unlock
    }
  }
}
于 2012-12-28T13:28:45.753 回答