-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternDesign.kt
More file actions
731 lines (613 loc) · 22.2 KB
/
PatternDesign.kt
File metadata and controls
731 lines (613 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/**
* **CATEGORÍAS DE PATRONES**
*
* 1. Creacionales: Patrones para creación de objetos
* 2. Estructurales: Patrones para composición de objetos
* 3. Comportamiento: Patrones para comunicación entre objetos
* 4. Arquitectónicos: Patrones para estructura de sistemas
*/
object DesignPatternsCatalog {
// ==================================================
// PATRONES CREACIONALES
// ==================================================
object CreationalPatterns {
/**
* **Singleton**: Garantiza una única instancia global
*/
object Singleton {
private var instance: Singleton? = null
fun getInstance(): Singleton {
return instance ?: synchronized(this) {
instance ?: Singleton().also { instance = it }
}
}
}
/**
* **Factory**: Encapsula creación de objetos relacionados
*/
object Factory {
interface Vehicle {
fun drive()
}
class Car : Vehicle {
override fun drive() = println("Driving car")
}
class Truck : Vehicle {
override fun drive() = println("Driving truck")
}
object VehicleFactory {
fun createVehicle(type: String): Vehicle = when (type) {
"car" -> Car()
"truck" -> Truck()
else -> throw IllegalArgumentException("Invalid type")
}
}
}
/**
* **Builder**: Construye objetos complejos paso a paso
*/
object Builder {
data class Computer(
val cpu: String,
val ram: Int,
val storage: Int,
val gpu: String?
)
class ComputerBuilder {
private var cpu: String = "i5"
private var ram: Int = 8
private var storage: Int = 256
private var gpu: String? = null
fun setCpu(cpu: String) = apply { this.cpu = cpu }
fun setRam(ram: Int) = apply { this.ram = ram }
fun setStorage(storage: Int) = apply { this.storage = storage }
fun setGpu(gpu: String) = apply { this.gpu = gpu }
fun build() = Computer(cpu, ram, storage, gpu)
}
}
/**
* **Prototype**: Crea nuevos objetos clonando existentes
*/
object Prototype {
abstract class Shape : Cloneable {
var id: String? = null
var type: String? = null
abstract fun draw()
public override fun clone(): Any {
return super.clone()
}
}
class Rectangle : Shape() {
override fun draw() = println("Drawing Rectangle")
}
}
/**
* **ObjectPool**: Reutiliza objetos costosos en creación
*/
object ObjectPool {
class DatabaseConnection {
init {
println("Creating DB connection (expensive operation)")
}
fun query(sql: String) = println("Executing: $sql")
}
class ConnectionPool(private val size: Int) {
private val available = mutableListOf<DatabaseConnection>()
private val inUse = mutableListOf<DatabaseConnection>()
init {
repeat(size) { available.add(DatabaseConnection()) }
}
fun acquire(): DatabaseConnection {
if (available.isEmpty()) {
println("Creating extra connection")
return DatabaseConnection()
}
val conn = available.removeAt(0)
inUse.add(conn)
return conn
}
fun release(conn: DatabaseConnection) {
inUse.remove(conn)
if (available.size < size) available.add(conn)
}
}
}
/**
* **AbstractFactory**: Crea familias de objetos relacionados
*/
object AbstractFactory {
interface Button {
fun render()
}
interface Checkbox {
fun render()
}
// Windows Family
class WinButton : Button {
override fun render() = println("Windows button")
}
class WinCheckbox : Checkbox {
override fun render() = println("Windows checkbox")
}
// MacOS Family
class MacButton : Button {
override fun render() = println("macOS button")
}
class MacCheckbox : Checkbox {
override fun render() = println("macOS checkbox")
}
interface GUIFactory {
fun createButton(): Button
fun createCheckbox(): Checkbox
}
class WinFactory : GUIFactory {
override fun createButton() = WinButton()
override fun createCheckbox() = WinCheckbox()
}
class MacFactory : GUIFactory {
override fun createButton() = MacButton()
override fun createCheckbox() = MacCheckbox()
}
}
/**
* **DependencyInjection**: Inyecta dependencias externamente
*/
object DependencyInjection {
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) = println(message)
}
class UserService(private val logger: Logger) {
fun register(user: String) {
logger.log("Registering user: $user")
}
}
}
}
// ==================================================
// PATRONES ESTRUCTURALES
// ==================================================
object StructuralPatterns {
/**
* **Decorator**: Añade funcionalidades dinámicamente
*/
object Decorator {
interface Coffee {
fun cost(): Double
}
class SimpleCoffee : Coffee {
override fun cost() = 2.0
}
class MilkDecorator(private val coffee: Coffee) : Coffee {
override fun cost() = coffee.cost() + 0.5
}
class SugarDecorator(private val coffee: Coffee) : Coffee {
override fun cost() = coffee.cost() + 0.2
}
}
/**
* **Adapter**: Convierte interfaces incompatibles
*/
object Adapter {
interface ModernPrinter {
fun printDocument(content: String)
}
class LegacyPrinter {
fun print(text: String) = println("Legacy printing: $text")
}
class PrinterAdapter(private val legacyPrinter: LegacyPrinter) : ModernPrinter {
override fun printDocument(content: String) {
legacyPrinter.print(content)
}
}
}
/**
* **Facade**: Simplifica interfaces complejas
*/
object Facade {
class CPU {
fun process() = println("Processing data")
}
class Memory {
fun load() = println("Loading memory")
}
class HardDrive {
fun read() = println("Reading disk")
}
class ComputerFacade {
private val cpu = CPU()
private val memory = Memory()
private val hdd = HardDrive()
fun start() {
memory.load()
hdd.read()
cpu.process()
}
}
}
/**
* **Proxy**: Controla acceso a objetos
*/
object Proxy {
interface Image {
fun display()
}
class RealImage(private val filename: String) : Image {
init {
loadFromDisk()
}
private fun loadFromDisk() = println("Loading $filename")
override fun display() = println("Displaying $filename")
}
class ImageProxy(private val filename: String) : Image {
private var realImage: RealImage? = null
override fun display() {
if (realImage == null) realImage = RealImage(filename)
realImage!!.display()
}
}
}
/**
* **Bridge**: Separa abstracción de implementación
*/
object Bridge {
interface Renderer {
fun renderCircle(radius: Int)
}
class VectorRenderer : Renderer {
override fun renderCircle(radius: Int) =
println("Drawing circle of radius $radius with vectors")
}
class RasterRenderer : Renderer {
override fun renderCircle(radius: Int) =
println("Drawing circle of radius $radius with pixels")
}
abstract class Shape(protected val renderer: Renderer) {
abstract fun draw()
}
class Circle(private val radius: Int, renderer: Renderer) : Shape(renderer) {
override fun draw() = renderer.renderCircle(radius)
}
}
/**
* **Module**: Organiza código en módulos
*/
object Module {
object MathUtils {
fun sum(a: Int, b: Int) = a + b
fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
}
object StringUtils {
fun reverse(s: String) = s.reversed()
fun isPalindrome(s: String) = s.equals(s.reversed(), ignoreCase = true)
}
}
/**
* **Composite**: Trata objetos individuales y compuestos uniformemente
*/
object Composite {
interface Graphic {
fun draw()
}
class Circle : Graphic {
override fun draw() = println("Drawing circle")
}
class CompositeGraphic : Graphic {
private val children = mutableListOf<Graphic>()
fun add(graphic: Graphic) = children.add(graphic)
fun remove(graphic: Graphic) = children.remove(graphic)
override fun draw() {
println("Composite:")
children.forEach { it.draw() }
}
}
}
/**
* **Flyweight**: Comparte objetos para reducir memoria
*/
object Flyweight {
data class TreeType(val name: String, val color: String)
class TreeFactory {
private val treeTypes = mutableMapOf<String, TreeType>()
fun getTreeType(name: String, color: String): TreeType {
return treeTypes.getOrPut("$name-$color") { TreeType(name, color) }
}
}
class Tree(
private val x: Int,
private val y: Int,
private val type: TreeType
) {
fun draw() = println("Drawing ${type.name} at ($x, $y)")
}
}
}
// ==================================================
// PATRONES DE COMPORTAMIENTO
// ==================================================
object BehavioralPatterns {
/**
* **Observer**: Notifica cambios a dependientes
*/
object Observer {
interface EventListener {
fun update(event: String)
}
class EventManager {
private val listeners = mutableMapOf<String, MutableList<EventListener>>()
fun subscribe(eventType: String, listener: EventListener) {
listeners.getOrPut(eventType) { mutableListOf() }.add(listener)
}
fun notify(eventType: String, data: String) {
listeners[eventType]?.forEach { it.update(data) }
}
}
}
/**
* **Strategy**: Algoritmos intercambiables
*/
object Strategy {
interface Compression {
fun compress(file: String)
}
class ZipCompression : Compression {
override fun compress(file: String) = println("Compressing $file to ZIP")
}
class RarCompression : Compression {
override fun compress(file: String) = println("Compressing $file to RAR")
}
class Compressor(private var strategy: Compression) {
fun setStrategy(strategy: Compression) {
this.strategy = strategy
}
fun compressFile(file: String) = strategy.compress(file)
}
}
/**
* **Command**: Encapsula solicitudes como objetos
*/
object Command {
interface Command {
fun execute()
}
class Light {
fun on() = println("Light on")
}
class LightOnCommand(private val light: Light) : Command {
override fun execute() = light.on()
}
class RemoteControl {
fun submit(command: Command) = command.execute()
}
}
/**
* **ChainOfResponsibility**: Encadena manejadores
*/
object ChainOfResponsibility {
abstract class Handler {
var next: Handler? = null
abstract fun handle(request: Int)
protected fun forward(request: Int) {
next?.handle(request)
}
}
class PositiveHandler : Handler() {
override fun handle(request: Int) {
if (request > 0) println("Positive handler: $request")
else forward(request)
}
}
}
/**
* **Interpreter**: Evalúa expresiones en lenguaje
*/
object Interpreter {
interface Expression {
fun interpret(): Int
}
class Number(private val value: Int) : Expression {
override fun interpret() = value
}
class Add(private val left: Expression, private val right: Expression) : Expression {
override fun interpret() = left.interpret() + right.interpret()
}
}
/**
* **TemplateMethod**: Define esqueleto de algoritmo
*/
object TemplateMethod {
abstract class Game {
abstract fun initialize()
abstract fun startPlay()
abstract fun endPlay()
fun play() {
initialize()
startPlay()
endPlay()
}
}
class Chess : Game() {
override fun initialize() = println("Chess initialized")
override fun startPlay() = println("Chess started")
override fun endPlay() = println("Chess finished")
}
}
/**
* **Iterator**: Acceso secuencial a colecciones
*/
object IteratorPattern {
class BookCollection(private val books: List<String>) {
fun createIterator() = BookIterator(books)
}
class BookIterator(private val books: List<String>) : Iterator<String> {
private var index = 0
override fun hasNext() = index < books.size
override fun next() = books[index++]
}
}
/**
* **Memento**: Captura y restaura estado interno
*/
object Memento {
class Editor {
private var content = ""
fun write(text: String) {
content += text
}
fun getContent() = content
fun save() = EditorMemento(content)
fun restore(memento: EditorMemento) {
content = memento.getState()
}
}
class EditorMemento(private val state: String) {
fun getState() = state
}
}
/**
* **Mediator**: Centraliza comunicación compleja
*/
object Mediator {
class ChatUser(private val mediator: ChatMediator, val name: String) {
fun send(message: String) = mediator.sendMessage(this, message)
fun receive(message: String) = println("$name received: $message")
}
class ChatMediator {
private val users = mutableListOf<ChatUser>()
fun addUser(user: ChatUser) = users.add(user)
fun sendMessage(sender: ChatUser, message: String) {
users.filter { it != sender }.forEach { it.receive("${sender.name}: $message") }
}
}
}
/**
* **Visitor**: Añade operaciones sin modificar clases
*/
object Visitor {
interface ReportVisitor<T> {
fun visit(element: Element): T
}
interface Element {
fun <T> accept(visitor: ReportVisitor<T>): T
}
class FixedPriceContract(val costPerYear: Long) : Element {
override fun <T> accept(visitor: ReportVisitor<T>) = visitor.visit(this)
}
class CostReportVisitor : ReportVisitor<String> {
override fun visit(element: FixedPriceContract) = "Cost: ${element.costPerYear}"
}
}
/**
* **State**: Cambia comportamiento con estado interno
*/
object State {
interface State {
fun handle(context: Context)
}
class Context(var state: State) {
fun request() = state.handle(this)
}
class StateA : State {
override fun handle(context: Context) {
println("Handling in State A")
context.state = StateB()
}
}
class StateB : State {
override fun handle(context: Context) {
println("Handling in State B")
context.state = StateA()
}
}
}
/**
* **NullObject**: Objeto predeterminado para evitar nulos
*/
object NullObject {
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) = println("LOG: $message")
}
class NullLogger : Logger {
override fun log(message: String) { /* No hace nada */
}
}
class Service(private val logger: Logger) {
fun doOperation() {
logger.log("Operation started")
// ... lógica
}
}
}
}
// ==================================================
// PATRONES ARQUITECTÓNICOS
// ==================================================
object ArchitecturalPatterns {
/**
* **Repository**: Abstracción de acceso a datos
*/
object RepositoryPattern {
interface UserRepository {
fun findById(id: Int): User?
fun save(user: User)
}
class InMemoryUserRepository : UserRepository {
private val users = mutableMapOf<Int, User>()
override fun findById(id: Int) = users[id]
override fun save(user: User) {
users[user.id] = user
}
}
data class User(val id: Int, val name: String, val email: String)
class UserService(private val userRepository: UserRepository) {
fun getUserEmail(id: Int) = userRepository.findById(id)?.email
}
}
/**
* **CQRS**: Separa comandos (escritura) de queries (lectura)
*/
object CQRS {
// Commands
interface CommandHandler<TCommand> {
fun handle(command: TCommand)
}
class CreateUserCommand(val name: String, val email: String)
class CreateUserHandler : CommandHandler<CreateUserCommand> {
override fun handle(command: CreateUserCommand) {
println("Creating user: ${command.name}")
// Lógica de creación
}
}
// Queries
interface QueryHandler<TQuery, TResult> {
fun handle(query: TQuery): TResult
}
class GetUserEmailQuery(val userId: Int)
class GetUserEmailHandler : QueryHandler<GetUserEmailQuery, String?> {
override fun handle(query: GetUserEmailQuery): String? {
// Lógica para obtener email
return "user${query.userId}@example.com"
}
}
// Bus
class CommandQueryBus {
private val handlers = mutableMapOf<Class<*>, Any>()
fun <TCommand> registerHandler(
commandType: Class<TCommand>,
handler: CommandHandler<TCommand>
) {
handlers[commandType] = handler
}
fun <TCommand> send(command: TCommand) {
val handler = handlers[command!!::class.java] as CommandHandler<TCommand>
handler.handle(command)
}
}
}
}
}