Young Devs Bin
๐Ÿ“ Today I Learned

Factory Pattern: One Place to Build Anything

ยท2 min readยท#today-i-learned#design-pattern#kotlin#android

Third pattern this week: Factory. The problem was a vehicle sensor system โ€” camera, LiDAR, and radar each initialize differently, and without Factory every caller that creates a sensor ends up needing to know those details.

  • Factory separates "what I want" from "how it's built" โ€” the caller just passes a type and gets back the right object, no constructor knowledge needed
  • In Kotlin, object is the right shape for a Factory โ€” there's no state to hold and no reason to ever have more than one instance
  • Adding a new sensor type means writing one new class and adding one line to the factory โ€” nothing else has to change, which is Open/Closed in practice
  • A manager class sits above the factory and handles lifecycle separately โ€” creation, lifecycle, and per-sensor logic each stay in their own place
  • Failure handling belongs in a callback, not a buried return value โ€” that way the manager decides what happens next instead of the sensor guessing
  • For sensors that need warm-up time, initialization becomes a suspend function launched on IO โ€” no blocking, no manual threading
  • Testing without going through the factory just needs a constructor parameter with a default empty list, so mocks can be injected directly