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(sid: String, upperCase: Boolean): ProductWithFactory {
return ProductWithFactory(if (upperCase) sid.toUpperCase() else sid.toLowerCase())
}
}
}
fun main() {
val lawnMover = RegularProduct("LMW0918")
println(lawnMover.skuId)
var trimmer = RegularProduct("ptrim041", true)
println(trimmer.skuId)
val lawnMoverWithFactory = ProductWithFactory.getProduct("f_LMW0918")
println(lawnMoverWithFactory.sid)
var trimmerWithFactory = ProductWithFactory.getProduct("f_ptrim041", true)
println(trimmerWithFactory.sid)
}
We also have a ProductWithFactory which has a private constructor which does not allow anyone to create instances knowing only the type data.
However we have a companion object which helps us to build methods that act as a factory which creates the objects for us
The advantage of this model is that we get to have more control on the number of objects that we can create and allow creation only if certain conditions are met etc.
Comments
Post a Comment