クラスにプラグインできるメソッドを使用して、軽量のインターフェイスを作成したいと思います。これがScalaの短い例です:
class DB {
def find(id: String) = ...
}
trait Transformation extends DB {
def transform(obj: String): String
override def find(id: String) =
transform(super.find(id))
}
trait Cache extends DB {
val cache = Cache()
override def find(id: String) = {
...
if (cache.contains(id))
cache.find(id)
else {
cache.set(id, super.find(id))
cache.get(id)
}
}
}
これらのクラス(特性)を使用して、Transformation、Cache、またはその両方を使用してDBクラスをインスタンス化できます。Transformationには抽象メソッドtransformがあり、それでも具象クラスに実装する必要があることに注意してください。
new DB() with Transformation {
def transform(obj: String): obj.toLower()
}
new DB() with Cache
new DB() with Transformation with Cache {
def transform(obj: String): obj.toLower()
}
Pythonでこのようなことを実現する方法はありますか?Python用のTraitsパッケージが存在することは知っていますが、その目的は異なっているようです。