w3resource

Kotlin Factory method pattern: Creating animal instances


Write a Kotlin object-oriented program that implements the factory method pattern by creating an abstract class Animal with subclasses Tiger and Lion. Use a factory class to create instances of animals based on user input.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Abstract Classes: Understanding how abstract classes provide a blueprint for subclasses.
  • Inheritance: Creating subclasses that extend an abstract class and implement its methods.
  • Factory Method Pattern: Using a factory class to create objects dynamically based on user input.
  • When Expression: Implementing decision-making logic using the when expression.
  • Nullable Types: Handling nullability in Kotlin when an invalid input is given.

Hints (Try Before Looking at the Solution!)

Try to solve the problem using these hints:

  • Hint 1: Define an abstract class Animal with an abstract function makeSound().
  • Hint 2: Create two subclasses, Tiger and Lion, that override the makeSound() method.
  • Hint 3: Implement a factory class AnimalFactory with a function createAnimal() that returns an appropriate subclass based on input.
  • Hint 4: Use the when expression in the factory method to determine which animal to instantiate.
  • Hint 5: In the main() function, create an instance of AnimalFactory, get user input, create the animal, and call its makeSound() method.

Sample Solution:

Kotlin Code:

abstract class Animal {
    abstract fun makeSound()
}

class Tiger : Animal() {
    override fun makeSound() {
        println("Tiger: Roar!")
    }
}

class Lion : Animal() {
    override fun makeSound() {
        println("Lion: Roar!")
    }
}

class AnimalFactory {
    fun createAnimal(type: String): Animal? {
        return when (type) {
            "Tiger" -> Tiger()
            "Lion" -> Lion()
            else -> null
        }
    }
}

fun main() {
    val animalFactory = AnimalFactory()
    val userInput = "Lion"
    //val userInput = "Tiger"
    println("Type of animal (Tiger or Lion): $userInput")
    
    val animal = animalFactory.createAnimal(userInput.orEmpty())
    animal?.makeSound()
}

Sample Output:

Type of animal (Tiger or Lion): Lion
Lion: Roar!

Explanation:

In the above exercise -

  • First, we create an abstract class "Animal" that defines common behavior. It has an abstract method makeSound().
  • The "Tiger" and "Lion" classes are subclasses of Animal and provide their own implementations of the "makeSound()" method.
  • The "AnimalFactory" class acts as a factory class. It has a method "createAnimal()" that takes a type (user input) and returns an instance of the corresponding animal. In this case, it creates instances of Tiger and Lion based on user input.
  • In the main() function, we create an AnimalFactory instance. We prompt the user to enter the type of animal they want to make. Based on user input, we use the factory class to generate an animal object. We then call the makeSound() method on the created animal object to demonstrate its behavior.

Kotlin Editor:


Previous: Modifying component behavior.
Next: Implementing subscription events.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.