我有一個抽象類影像過濾器:
abstract class ImageFilter {
internal abstract val size: Int
fun applyForImage(image: BmpImage) {
//here size is used to calculate the boundaries
//somewhere here applyForOnePixel(data) is called
//...
}
abstract fun applyForOnePixel(data: Array<Array<RGBColor>>): RGBColor
}
實作子類是沒有問題的,但是,為了呼叫applyForImage,需要創建一個實體,例如,這樣
GrayscaleFilter().applyForImage(img)
但是,我想這樣做
GrayscaleFilter.applyForImage(img)
我知道我必須使用伴隨物件,但是如果不能在伴隨物件中使用抽象,我如何讓子類實作 applyForOnePixel 并指定大小?
uj5u.com熱心網友回復:
如果您GrayscaleFilter不應該以任何方式修改,您可以將其定義為 aobject而不是 a class。
object GrayscaleFilter: ImageFilter() {
override val size: Int = TODO("Not yet implemented")
override fun applyForOnePixel(data: Array<Array<RGBColor>>): RGBColor {
TODO("Not yet implemented")
}
}
這樣一個實體在運行時可用,可以根據需要訪問,即:
GrayscaleFilter.applyForImage(img)
但是請注意,這有影響。你基本上是在處理一個單身人士。因此,如果您可以以任何方式修改實體,例如通過具有可訪問var欄位,這些更改是全域的!
在一個側節點上,也許您想輪換呼叫順序,以方便讀取呼叫,例如:
fun BmpImage.applyFilter(filter: ImageFilter) = filter.applyForImage(this)
fun main() {
val image: BmpImage = TODO("Not yet implemented")
image.applyFilter(GrayscaleFilter)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430949.html
上一篇:如何更簡潔地撰寫更新類引數值?
