Created
February 16, 2026 08:45
-
-
Save aroranubhav/8c1a6169a99350e82da892f2763f354a to your computer and use it in GitHub Desktop.
Class Creation with Factory pattern.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Factory Pattern: A creation design pattern that delegates object creation to a factory. | |
| * | |
| * USE WHEN: Creating objects that require constructor parameters, making reflection impractical | |
| * or impossible (since reflection only works cleanly with no-arg constructors). | |
| * | |
| * In this example, the Factory interface encapsulates the creation logic, allowing: | |
| * - Parameterized constructors (v1, v2) | |
| * - Dependency injection at creation time | |
| * - Type-safe object creation with compile-time checks | |
| * - Custom initialization logic beyond simple constructors | |
| * | |
| * Use case: Android's ViewModelProvider uses Factory when ViewModels need dependencies | |
| * (e.g., Repository, SavedStateHandle). The factory knows how to construct the ViewModel | |
| * with the right parameters. | |
| * | |
| * Trade-offs: | |
| * - Pro: Supports parameterized constructors, compile-time type safety | |
| * - Pro: Faster than reflection, can include complex initialization logic | |
| * - Con: Requires boilerplate Factory implementation for each class | |
| * | |
| * Note: Using 'fun interface' (SAM) makes it concise - can use lambda syntax instead of | |
| * creating anonymous class implementations. | |
| */ | |
| class ClassCreationWithFactory( | |
| private val v1: Int, | |
| private val v2: String | |
| ) { | |
| fun doSomeTask() { | |
| print("Inside class created via factory method, with values $v1 and $v2") | |
| } | |
| } | |
| fun interface Factory<T> { | |
| fun create(): T | |
| } | |
| fun <T> getClassInstance(factory: Factory<T>): T { | |
| return factory.create() | |
| } | |
| fun main() { | |
| val cI = getClassInstance(Factory { | |
| return@Factory ClassCreationWithFactory(101, "Maxi") | |
| }) | |
| cI.doSomeTask() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment