디자인 패턴이란 사실 자주 발생하는 문제에 대한 검증된 해결책이다
생성 패턴
언제, 어떻게 객체를 생성 할 지에 관한 디자인 패턴
싱글톤 패턴
object singleton { ... }팩토리 메서드 패턴
interface Car class SportCar: car class NomarlCar: car fun factory(type): Car { return when(type) { "sport" -> SportCar() "normal" -> NormalCar() else -> throw Excpetion() } }정적 팩토리 메서드
class Server(port: Long) { companion object { fun withPort(port: Long) = Server(port) } }추상 팩토리
class SportEngine class SportMission class NormalEngine class NormalMission fun factory(type): Car { return when(type) { "sport" -> SportCar(SportEngine(), SportMission()) "normal" -> NormalCar(NormalEngine(), NormalMission()) else -> throw Excpetion() } }빌더 패턴
class mail( val to: List<String>, val cc: List<String> = emptyListOf(), val title: String = "" )프로토타입 패턴
data class User(val a: String, val b: String) // b is new field val userList: MutableList<User> fun addNewUser(oldUser: User, b: String) { userList.add(oldUser.copy(b = b)) }구조 패턴
객체 간의 관계를 다루는 디자인 패턴
데코레이터 패턴
interface Ifce class Default: Ifce class AddOn1(privat val impl: Ifce): Ifce by impl class AddOn2(privat val impl: Ifce): Ifce by impl --- use val default = Default() val addOn1 = AddOn1(default) val addOn2 = AddOn2(addOn2)어댑터 패턴
브릿지 패턴
interface Weapon interface Shied class Soldier(w: Weapon, s: Shied) val normalSoldier = Soldier(normalWeapon, normalShied) val fireSoldier = Soldier(fireWeapon, normalShied) val Shieder = Soldier(normalWeapon, TopShied)합성 패턴
동일한 행동을 하는 여러 집합을 다루기 위한 패턴
코틀린에서는 상속과 vararg를 이용하여 쉽게 구현
example
interface Soldier
class NormalSoldier: Soldier
class Squad(val list: List<Soldier>): Soldier {
constructor(vararg units: Soldier) = list = units.toList()
}
퍼사드 패턴
경량(flyweight) 패턴
프록시 패턴
동작 패턴
함수형 프로그래밍
반응형 프로그래밍과 코루틴
동시성 디자인 패턴