Patrones de diseño en Swift: técnicas avanzadas y ejemplos

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Patrones de diseño avanzados en Swift: de la teoría a la práctica

Los patrones de diseño no son solo conceptos abstractos, sino soluciones probadas a lo largo del tiempo para problemas típicos. Si ya dominas los patrones básicos (Singleton, Delegate, MVC) y trabajas en aplicaciones complejas para iOS/macOS, es hora de pasar al siguiente nivel. En este artículo analizaremos cuatro patrones avanzados: Builder, Strategy, Observer (a través de Combine) y Coordinator. Cada patrón se ilustrará con código real en Swift y consejos para integrarlos en proyectos existentes.



1. Builder — configuración flexible de objetos complejos

El patrón Builder es ideal para crear objetos con múltiples parámetros opcionales. En lugar de largos inicializadores con decenas de parámetros, utilizas una construcción paso a paso.

Ejemplo: configuración 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("Error") .setMessage("No se pudieron cargar los datos") .addAction(title: "OK", style: .default) .addAction(title: "Reintentar", style: .cancel) .build()present(alert, animated: true)

Cuándo usarlo: al crear configuradores, ViewControllers complejos o modelos de datos con muchas opciones.



2. Strategy — cambio de algoritmos sobre la marcha

El patrón Strategy permite encapsular una familia de algoritmos y hacerlos intercambiables. Esto es especialmente útil para procesar pagos, validar datos o renderizar.

Ejemplo: sistema de filtrado de contenido

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"]

Consejo: combina Strategy con el método Factory para seleccionar la estrategia según las preferencias del usuario.



3. Observer a través de Combine — re

Blogs

Book Recommendations