Home > database >  How to better organize the hierarchy of classes
How to better organize the hierarchy of classes

Time:02-20

I have an abstract class Image Filter:

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
}

There is no problem implementing the child class, however, in order to call applyForImage, it is necessary to create an instance, for example, in this way

GrayscaleFilter().applyForImage(img)

However, I want to do it this way

GrayscaleFilter.applyForImage(img)

I understand that I have to use companion object, but how do I get child classes to implement applyForOnePixel and specify size if you can't use abstract inside the companion object?

CodePudding user response:

If your GrayscaleFilter should not be modifiable in any way, you can define it as an object instead of 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")
    }
}

This way a single instance is available during runtime, which can be accessed as you desire, namely:

GrayscaleFilter.applyForImage(img)

Note however, that this has implications. You're basically dealing with a singleton. Thus, if you can modify the instance in any way, e.g. by having accessible var fields, these changes are global!


On a side node, maybe you want to rotate the call order, to ease reading of the calls, e.g.:

fun BmpImage.applyFilter(filter: ImageFilter) = filter.applyForImage(this)

fun main() {
    val image: BmpImage = TODO("Not yet implemented")

    image.applyFilter(GrayscaleFilter)
}
  • Related