DEV Community

sunj
sunj

Posted on

Kotlin object singleton patton, 2024-03-18

//싱글톤 패턴 적용, 카팩토리라는 실행 시 한번 객체 생성, 불필요한 메모리 막을 수 있음
object CarFactory {
   val cars = mutableListPf<Car>()

   fun makeCar(horsePower : Int): Car{
      val car = Car(horsePower)
      cars.add(car)
      return car
   }
}

data class Car(val horsePower : Int)

fun main(){
   val car1 = CarFactory.makeCar(10)
   val car2 = CarFactory.makeCar(300)

   println(car1)
   println(car2)
   println(CarFactory.cars.size.toString())
}
Enter fullscreen mode Exit fullscreen mode

터미널 결과
Car(horsePower=10)
Car(horsePower=300)
2

참조 : Code with Joyce

Top comments (0)