Issue
Do I implement the Adapter pattern in this way? It's a display-port to VGA adapter.
interface DisplayPortSignal {
fun processSignal(signal: Int)
}
interface VgaSignal {
fun processSignal(signal: Int)
}
class GPU(private val displayPortSignal: DisplayPortSignal) {
fun sendSignal(signal: Int) {
println("Sending signal $signal")
displayPortSignal.processSignal(signal)
}
}
class Monitor: VgaSignal {
override fun processSignal(signal: Int) {
println("Signal ready: $signal")
}
}
As you see I have 2 types of signals. The GPU sends only display-port signals, but the monitor accepts VGA signals.
class SignalAdapter(private val vgaSignal: VgaSignal) : DisplayPortSignal {
override fun processSignal(signal: Int) {
vgaSignal.processSignal(signal)
}
}
I have an adapter, which converts one type of signal to another.
fun main() {
val monitor = Monitor()
val gpu = GPU(SignalAdapter(monitor))
val randomSignalNumber = Random()
for (i in 0..100) {
gpu.sendSignal(randomSignalNumber.nextInt(100))
}
}
I'm just confused have I implemented it in the right way? Thank you.
P.S. I've read articles about the adapter pattern, but when you implement it yourself, it's ok to have some confusion about the implementation. Because there may be some little gaps in the code or anything else. So you can either answer like "fix this" or "this part is not implemented in the right way" or just give some advice. Just wondering, what is inappropriate in this question, that you're voting to close it?
Solution
Your example is very abstract, but it doesn't quite make sense. You simply pass through the processing implementation exactly as if they are equivalent. It would also help to not name the functions exactly the same way. Presumably the two types of signal processors (that you call Signals, which is confusing) take different format inputs.
I would edit as follows to better illustrate the adapter pattern.
interface DisplayPortSignalProcessor {
fun processDisplayPortSignal(signal: Int)
}
interface VgaSignalProcessor {
fun processVgaSignal(signal: Int)
}
class Gpu(private val displayPortSignalProcessor: DisplayPortSignalProcessor) {
fun sendDisplayPortSignal(signal: Int) {
println("Sending signal $signal")
displayPortSignalProcessor.processDisplayPortSignal(signal)
}
}
class VgaMonitor: VgaSignalProcessor {
override fun processVgaSignal(signal: Int) {
println("Signal ready: $signal")
}
}
class VgaToDisplayPortSignalAdapter(private val vgaSignal: VgaSignalProcessor) : DisplayPortSignalProcessor {
override fun processDisplayPortSignal(signal: Int) {
val vgaFormatSignal = signal * 2 // simulate some sort of conversion of the input
vgaSignal.processVgaSignal(vgaFormatSignal)
}
}
fun main() {
val monitor = VgaMonitor()
val gpu = Gpu(VgaToDisplayPortSignalAdapter(monitor))
val randomSignalNumber = Random.Default
repeat(10) {
gpu.sendDisplayPortSignal(randomSignalNumber.nextInt(100))
}
}
Answered By - Tenfour04
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.