Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created February 17, 2022 09:09
Show Gist options
  • Save rommansabbir/7f6485c32546534d12f5b2c2936bd210 to your computer and use it in GitHub Desktop.
Save rommansabbir/7f6485c32546534d12f5b2c2936bd210 to your computer and use it in GitHub Desktop.
Delegation
/**
* Our interface that has only one method [Delegation.print].
* Who inherit [Delegation] might have different implementation.
* So we are declaring [Delegation.print] without any kind of parameter.
*/
interface Delegation {
fun print()
}
/**
* Implementation of [Delegation]. We are printing an [Int] value.
*
* @param x [Int] value to print.
*/
class DelegationImpl(private val x: Int) : Delegation {
override fun print() {
println(x)
}
}
/**
* Another Implementation of [Delegation]. We are printing an [String] value.
*
* @param value [String] value to print.
*/
class DelegationImpl2(private val value: String) : Delegation {
override fun print() {
println(value)
}
}
/**
* Our delegation class. Using the keyword **by** we are delegating it.
*
* Note: [Derived] takes [Delegation] object as a parameter and return the same object.
* So that client can access the public functions of [Delegation]
*/
class Derived(private val b: Delegation) : Delegation by b
/**
* Our another delegation class.
*
* Note: We are overriding the public method [Delegation.print] and we are printing our message
* instead of the [Delegation]'s one. [AnotherDerived.print] will always print our message.
*/
class AnotherDerived(private val b: Delegation) : Delegation by b {
override fun print() {
println("We are printing our custom message instead of the client one.")
}
}
class DelegationExample {
companion object {
@JvmStatic
fun main(args: Array<String>) {
/**
* Create instances of [Delegation]
*/
val delegation1 = DelegationImpl(5)
val delegation2 = DelegationImpl2("Test")
/**
* Accessing [Delegation.print] by using [Derived] class instead of directly accessing it.
*/
Derived(delegation1).print() // Output -> 5
Derived(delegation2).print() // Output -> "Test"
/**
* Another delegation to print our custom message instead of "Test".
*/
AnotherDerived(delegation2).print() // Output -> "We are printing our custom message instead of the client one."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment