Created
December 31, 2023 18:49
-
-
Save mRB0/75f250195e872f578215507f2344a82b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example | |
import java.io.File | |
import java.util.* | |
typealias ResultType = String | |
interface Processor<T : Any> { | |
fun getType(): Class<T> | |
fun handle(specimen: T): ResultType | |
fun canHandle(specimen: Any): Boolean { | |
return getType().isInstance(specimen) | |
} | |
companion object { | |
private val processorList: List<Processor<*>> = listOf( | |
DateProcessor, | |
FileProcessor, | |
CharSequenceProcessor | |
) | |
fun <ProcessorType : Any, SpecimenType : ProcessorType> getTheRightProcessor(specimen: SpecimenType): Processor<ProcessorType> { | |
val matchingProcessor: Processor<*> = processorList.first { | |
it.canHandle(specimen) | |
} | |
@Suppress("UNCHECKED_CAST") | |
return matchingProcessor as Processor<ProcessorType> | |
} | |
fun <SpecimenType : Any> handle(specimen: SpecimenType) = | |
getTheRightProcessor(specimen).handle(specimen) | |
fun <SpecimenType : Any> getHandler(specimen: SpecimenType): () -> ResultType { | |
return { | |
handle(specimen) | |
} | |
} | |
} | |
} | |
object DateProcessor : Processor<Date> { | |
override fun getType(): Class<Date> { | |
return Date::class.java | |
} | |
override fun handle(specimen: Date): ResultType { | |
return "handler = $this; date = $specimen" | |
} | |
} | |
object FileProcessor : Processor<File> { | |
override fun getType(): Class<File> { | |
return File::class.java | |
} | |
override fun handle(specimen: File): ResultType { | |
return "handler = $this; path = ${specimen.path}; exists = ${specimen.exists()}" | |
} | |
} | |
object CharSequenceProcessor : Processor<CharSequence> { | |
override fun getType(): Class<CharSequence> { | |
return CharSequence::class.java | |
} | |
override fun handle(specimen: CharSequence): ResultType { | |
return "handler = $this; length = ${specimen.length}" | |
} | |
} | |
fun main() { | |
val sampleDate = Date() | |
val sampleFile = File("/windows/system32") | |
val sampleString = "This is a String which is-a CharSequence" | |
println("sampleDate: ${Processor.handle(sampleDate)}") | |
println("sampleFile: ${Processor.handle(sampleFile)}") | |
println("sampleString: ${Processor.handle(sampleString)}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment