Padrões Avançados de Design em Swift: da Teoria à Prática
Padrões de design não são apenas conceitos abstratos, mas soluções testadas pelo tempo para problemas típicos. Se você já domina os padrões básicos (Singleton, Delegate, MVC) e está trabalhando em aplicativos iOS/macOS complexos, é hora de passar para o próximo nível. Neste artigo, vamos explorar quatro padrões avançados: Builder, Strategy, Observer (via Combine) e Coordinator. Cada padrão será ilustrado com código real em Swift e dicas para integração em projetos existentes.
1. Builder — Configuração Flexível de Objetos Complexos
O padrão Builder é ideal para criar objetos com muitos parâmetros opcionais. Em vez de inicializadores longos com dezenas de parâmetros, você usa uma construção passo a passo.
Exemplo: Configuração de UIAlertController
class AlertBuilder { private var title: String? private var message: String? private var actions: [UIAlertAction] = [] private var preferredStyle: UIAlertController.Style = .alert
func setTitle(_ title: String) -> AlertBuilder { self.title = title return self }
func setMessage(_ message: String) -> AlertBuilder { self.message = message return self }
func addAction(title: String, style: UIAlertAction.Style = .default, handler: ((UIAlertAction) -> Void)? = nil) -> AlertBuilder { let action = UIAlertAction(title: title, style: style, handler: handler) actions.append(action) return self }
func setStyle(_ style: UIAlertController.Style) -> AlertBuilder { self.preferredStyle = style return self }
func build() -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) actions.forEach { alert.addAction($0) } return alert }}
// Usolet alert = AlertBuilder() .setTitle("Erro") .setMessage("Falha ao carregar dados") .addAction(title: "OK", style: .default) .addAction(title: "Tentar novamente", style: .cancel) .build()present(alert, animated: true)Quando usar: ao criar configuradores, ViewControllers complexos ou modelos de dados com muitas opções.
2. Strategy — Alternância de Algoritmos em Tempo Real
O padrão Strategy permite isolar uma família de algoritmos e torná-los intercambiáveis. Isso é especialmente útil para processamento de pagamentos, validação de dados ou renderização.
Exemplo: Sistema de Filtragem de Conteúdo
protocol FilterStrategy { func apply(to items: [String]) -> [String]}
class AlphabeticalFilter: FilterStrategy { func apply(to items: [String]) -> [String] { return items.sorted() }}
class LengthFilter: FilterStrategy { func apply(to items: [String]) -> [String] { return items.filter { $0.count > 5 } }}
class ContentManager { private var strategy: FilterStrategy
init(strategy: FilterStrategy) { self.strategy = strategy }
func setStrategy(_ strategy: FilterStrategy) { self.strategy = strategy }
func filter(items: [String]) -> [String] { return strategy.apply(to: items) }}
// Usolet manager = ContentManager(strategy: AlphabeticalFilter())let data = ["Swift", "Objective-C", "Kotlin", "Java", "Python"]print(manager.filter(items: data)) // ["Java", "Kotlin", "Objective-C", "Python", "Swift"]
manager.setStrategy(LengthFilter())print(manager.filter(items: data)) // ["Objective-C", "Python"]Dica: combine Strategy com o método de fábrica para selecionar a estratégia com base nas configurações do usuário.