Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bridge Design Pattern - Kotlin
class BridgeDesignPattern {
companion object {
@JvmStatic
fun main(args: Array<String>) {
// Send new text message
val textMessageSender: MessageSender = TextMessageSender()
val textMessage: Message = TextMessage(textMessageSender)
textMessage.send()
// Send new email message
val emailMessageSender: MessageSender = EmailMessageSender()
val emailMessage: Message = EmailMessage(emailMessageSender)
emailMessage.send()
}
}
}
/**
* Base class to send message.
* [Message] takes [MessageSender] instance as a parameter by following ** Has-A Relationship ** and ** Composition **.
*
* @param sender [MessageSender] instance to send message.
*/
abstract class Message(internal val sender: MessageSender) {
abstract fun send()
}
/**
* Impl of [Message] to send Text Message.
*
* @param messageSender, [MessageSender] instance to send message.
*/
class TextMessage(messageSender: MessageSender) : Message(messageSender) {
override fun send() {
sender.sendMessage()
}
}
/**
* Impl of [Message] to send Email Message.
*
* @param messageSender, [MessageSender] instance to send message.
*/
class EmailMessage(messageSender: MessageSender) : Message(messageSender) {
override fun send() {
sender.sendMessage()
}
}
/**
* Base of message sending implementation.
*/
interface MessageSender {
fun sendMessage()
}
/**
* Impl of [MessageSender], is responsible to send Text Message.
*/
class TextMessageSender : MessageSender {
override fun sendMessage() {
println("TextMessageSender: Sending text message...")
}
}
/**
* Impl of [MessageSender], is responsible to send Email Message.
*/
class EmailMessageSender : MessageSender {
override fun sendMessage() {
println("EmailMessageSender: Sending email message...")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment