add dril02 -exercise3

This commit is contained in:
Raffaele Mignone 2020-03-23 17:55:33 +01:00
parent ac35528eab
commit 477323d1dd
Signed by: norangebit
GPG Key ID: F5255658CB220573
6 changed files with 64 additions and 4 deletions

View File

@ -1,14 +1,15 @@
package drills.drill02.exercise2
import java.io.Serializable
import java.rmi.Remote
import java.rmi.RemoteException
import java.rmi.server.UnicastRemoteObject
interface Rev : Remote {
@Throws(RemoteException::class)
fun <T> executeTask(task: () -> T): T
fun <T : Serializable> executeTask(task: () -> T): T
}
class RevImpl : Rev, UnicastRemoteObject() {
override fun <T> executeTask(task: () -> T): T = task()
override fun <T : Serializable> executeTask(task: () -> T): T = task()
}

View File

@ -0,0 +1,11 @@
package drills.drill02.exercise3
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
class LogHandler(private val target: Any) : InvocationHandler {
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {
println("log: method '$method' has been invoked")
return method?.invoke(target, *(args ?: arrayOf())) ?: Unit
}
}

View File

@ -0,0 +1,15 @@
package drills.drill02.exercise3
fun main() {
val factory = MathFactory()
val math = factory.create()
val mathLog = factory.create(logger = true)
println("Enter two numbers:")
val a = readLine()?.toFloat() ?: 0f
val b = readLine()?.toFloat() ?: 0f
println("The sum is ${math.add(a, b)}.")
println("The sum is ${mathLog.add(a, b)}.")
}

View File

@ -0,0 +1,18 @@
package drills.drill02.exercise3
interface Math {
fun add(a: Float, b: Float): Float
fun sub(a: Float, b: Float): Float
fun mul(a: Float, b: Float): Float
fun div(a: Float, b: Float): Float
}
class MathImpl : Math {
override fun add(a: Float, b: Float): Float = a + b
override fun sub(a: Float, b: Float): Float = a - b
override fun mul(a: Float, b: Float): Float = a * b
override fun div(a: Float, b: Float): Float = a / b
}

View File

@ -0,0 +1,15 @@
package drills.drill02.exercise3
import java.lang.reflect.Proxy
class MathFactory {
fun create(logger: Boolean = false): Math {
return if (logger) {
Proxy.newProxyInstance(
this::class.java.classLoader,
arrayOf(Math::class.java),
LogHandler(MathImpl())
) as Math
} else MathImpl()
}
}

View File

@ -20,7 +20,7 @@ class Client(private val handler: () -> Unit) {
}
companion object {
fun lookup(name: String, port: Int = 4242): Remote =
Naming.lookup("rmi://localhost:$port/$name")
fun lookup(name: String, host: String = "localhost", port: Int = 4242): Remote =
Naming.lookup("rmi://$host:$port/$name")
}
}