joshua-r2
11/1/2017 - 3:02 PM

Companion Object - Basic Factory

A companion object can access internals of a class without requiring an instance of it. This is particularly useful in the Factory Design Pattern. Below is a simple example


//Simple LandRoverFactory
class LandRoverFactory private constructor(trim: String, color: String)
{
    companion object {


        fun buildRangeRoverSport(diesel: Boolean, color: String): LandRoverFactory
        {
            return LandRoverFactory(if (diesel) "TD6" else "HSE", color)
        }

        fun buildDiscovery(luxuryEdition: Boolean, color: String): LandRoverFactory
        {
            return LandRoverFactory(if(luxuryEdition) "HSE Luxury" else "SE", color)
        }
    }


}