Skip to main content

Posts

Showing posts with the label factory

Factory design pattern in Kotlin with companion objects

Factory Pattern The factory pattern helps the user to create the objects based on the inputs, so that the caller does not know how the object instances are created, instead focus on what are required to get me an instance of a given type. We start with a regular product, which has a constructor that takes the arguments and allows anyone to create the objects by invoking the appropriate constructor class RegularProduct { var skuId : String constructor ( sId : String ) { skuId = sId } constructor ( sId : String , upperCase : Boolean ) { skuId = if ( upperCase ) sId . toUpperCase () else sId . toLowerCase () } } //The private primary constructor restricts instantiation by any means other than factory class ProductWithFactory private constructor ( val sid : String ) { companion object { //Acts as a factory fun getProduct ( sid : String ): ProductWithFactory { return ProductWithFactory ( sid ) } fun getProduct ( si