Abstract factory

The abstract factory pattern works in a similar way to the factory method, but it's used for complex cases. According to this pattern, we have a factory that generates other factories. The following diagram illustrates types of hierarchy:

This diagram contains the MercedesFactory and HondaFactory classes, which implement the CarFactory interface. The FactoryProducer class contains the produceFactory method, which returns a new instance of the CarFactory type. The CarFactory interface, in turn, contains the createCar method, which returns an instance of the Car type. The Car interface is extended by the Mercedes and Honda interfaces, which are then implemented by certain classes such as Civic, Accord, E220, and E300.

The hierarchy of classes and interfaces displayed in the preceding diagram can be implemented as follows:

class FactoryProducer {
fun produceFactory(brand: Brand): Factory = when (brand) {
Brand.MERCEDES -> MercedesFactory()
Brand.HONDA -> HondaFactory()
Brand.MAZDA -> TODO()
Brand.BMW -> TODO()
}
}

The Factory interface looks like this:

interface Factory {
fun createCar(model: Model): Car
}

The classes that implement the Factory interface may look as follows:

class MercedesFactory : Factory {
override fun createCar(model: Model): Car = when (model) {
MercedesModel.E220 -> E220()
MercedesModel.E300 -> E300()
else -> TODO()
}
}

class HondaFactory : Factory {
override fun createCar(model: Model): Car = when (model) {
HondaModel.ACCORD -> Accord()
HondaModel.CIVIC -> Civic()
else -> TODO()
}
}

The Model interface looks like this:

interface Model

This can be implemented as follows:

enum class MercedesModel : Model {
E220,
E300
}

enum class HondaModel : Model {
ACCORD,
CIVIC
}

We can use this implementation of the abstract factory pattern, which may look like this:

fun main(args: Array<String>) {
val e220 = FactoryProducer().produceFactory(Brand.MERCEDES).createCar(MercedesModel.E220)
}
..................Content has been hidden....................

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