Padrões de Projeto em Kotlin: exemplos e prática

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Introdução aos Padrões de Projeto em Kotlin



Padrões de projeto (design patterns) são soluções comprovadas para problemas típicos de desenvolvimento. Na linguagem Kotlin, muitos padrões clássicos são implementados de forma mais concisa e segura graças a recursos integrados: null-safety, funções de extensão, corrotinas e um poderoso sistema de tipos.



Neste artigo, abordaremos três grupos de padrões: criacionais, estruturais e comportamentais — com exemplos reais em Kotlin. Você aprenderá como usá-los no desenvolvimento diário para criar uma arquitetura flexível e de fácil manutenção.



Padrões Criacionais (Creational)



1. Singleton (Singleton)

Em Kotlin, o singleton é implementado com a palavra-chave object. É um singleton lazy e thread-safe sem código extra.



object DatabaseConnection {    private val url = "jdbc:postgresql://localhost:5432/mydb"    private val user = "admin"    private val password = "secret"

fun connect(): String { return "Connected to $url as $user" }}

fun main() { println(DatabaseConnection.connect()) // Verificamos que é o mesmo objeto val ref1 = DatabaseConnection val ref2 = DatabaseConnection println(ref1 === ref2) // true}


Vantagem: não é necessário escrever synchronized ou volatile — o Kotlin garante uma única instância.



2. Factory Method (Método Fábrica)

Permite delegar a criação de objetos para subclasses. Em Kotlin, é conveniente usar sealed class e companion object.



sealed class Notification {    data class Email(val to: String, val subject: String) : Notification()    data class SMS(val phone: String, val message: String) : Notification()    data class Push(val deviceId: String, val title: String) : Notification()

companion object Factory { fun createEmail(to: String, subject: String): Notification = Email(to, subject) fun createSMS(phone: String, message: String): Notification = SMS(phone, message) fun createPush(deviceId: String, title: String): Notification = Push(deviceId, title) }}

fun send(notification: Notification) { when (notification) { is Notification.Email -> println("Email to ${notification.to}") is Notification.SMS -> println("SMS to ${notification.phone}") is Notification.Push -> println("Push to ${notification.deviceId}") }}

fun main() { val email = Notification.createEmail("user@example.com", "Hello") send(email)}


3. Builder (Construtor)

Em Kotlin, o Builder pode ser substituído por argumentos nomeados e valores padrão. Mas para objetos complexos com validação, o Builder clássico ainda é relevante.



class Pizza private constructor(    val size: String,    val cheese: Boolean,    val pepperoni: Boolean,    val mushrooms: Boolean) {    class Builder {        private var size: String = "Medium"        private var cheese: Boolean = false        private var pepperoni: Boolean = false        private var mushrooms: Boolean = false

fun size(size: String) = apply { this.size = size } fun cheese() = apply { this.cheese = true } fun pepperoni() = apply { this.pepperoni = true } fun mushrooms() = apply { this.mushrooms = true }

fun build(): Pizza { require(size in listOf("Small", "Medium", "Large")) { "Invalid size" } return Pizza(size, cheese, pepperoni, mushrooms) } }}

fun main() { val pizza = Pizza.Builder() .size("Large") .cheese() .pepperoni() .build() println("Pizza: ${pizza.size}, cheese=${pizza.cheese}, pepperoni=${pizza.pepperoni}")}


Padrões Estruturais (Structural)



4. Adapter (Adaptador)

O Adapter permite que objetos com

Blogs

Book Recommendations