Factory method

The factory method pattern is used to make the process of object creation more abstract by using the regular method of a special class instead of a constructor. This approach allows us to instantiate an object of a certain subtype at runtime. The following UML diagram shows the organization of classes and interfaces according to this pattern:

The preceding diagram contains the Mercedes class, which implements the Car interface. The CarFactory class is responsible for creating new instances of the Car type.

The implementation may look as follows:

class CarFactory {
fun createCar(brand: Brand): Car {
return when(brand) {
Brand.BMW -> BMW()
Brand.MERCEDES -> Mercedes()
Brand.HONDA -> Honda()
Brand.MAZDA -> Mazda()
}
}
}

The CarFactory class contains the createCar function, which returns an instance of the Car type:

interface Car
class Mercedes: Car
class BMW: Car
class Honda: Car
class Mazda: Car

The createCar method also takes an instance of Brand:

enum class Brand {
BMW,
MERCEDES,
HONDA,
MAZDA
}

We can use this implementation as follows:

fun main(args: Array<String>) {
val mercedes = CarFactory().createCar(Brand.MERCEDES)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.7.208