Facade Design Pattern in Kotlin

1. Definition

The Facade Design Pattern provides a unified interface to a set of interfaces in a subsystem. The facade defines higher-level operations that make the subsystem easier to use.

In this tutorial, we will learn how to implement a Facade Design Pattern using Kotlin programming language.

2. Problem Statement

Imagine building a home automation system where turning on "movie mode" involves dimming lights, lowering blinds, turning on the projector, and starting the movie. Interacting with each component separately can be tedious and error-prone.

3. Solution

Use the Facade pattern to provide a simplified interface that performs all necessary steps to turn on "movie mode". Clients interact with the facade, which then interacts with the individual subsystems.

4. Real-World Use Cases

1. Computer startups where several components like CPU, Memory, and Hard Drive work together.

2. E-commerce platforms, where placing an order involves payment processing, inventory management, and shipping.

5. Implementation Steps

1. Identify a complex subsystem that needs simplification.

2. Create a facade class with methods that offer simplified operations.

3. Let the facade class delegate calls to methods of the subsystem.

6. Implementation in Kotlin Programming

// Subsystems
class Lights {
    fun dim() {
        println("Lights dimmed.")
    }
}
class Blinds {
    fun lower() {
        println("Blinds lowered.")
    }
}
class Projector {
    fun turnOn() {
        println("Projector turned on.")
    }
}
class MoviePlayer {
    fun play() {
        println("Movie started playing.")
    }
}
// Facade
class HomeTheaterFacade(private val lights: Lights, private val blinds: Blinds, private val projector: Projector, private val moviePlayer: MoviePlayer) {
    fun watchMovie() {
        lights.dim()
        blinds.lower()
        projector.turnOn()
        moviePlayer.play()
    }
}
fun main() {
    val homeTheater = HomeTheaterFacade(Lights(), Blinds(), Projector(), MoviePlayer())
    homeTheater.watchMovie()
}

Output:

Lights dimmed.
Blinds lowered.
Projector turned on.
Movie started playing.

Explanation:

1. Lights, Blinds, Projector, and MoviePlayer are subsystems that have specific operations.

2. HomeTheaterFacade is the facade that provides the watchMovie operation, encapsulating the complexity of starting a movie session.

3. In the main function, we use the facade to watch a movie, abstracting away the underlying complexities.

7. When to use?

Use the Facade pattern when:

1. You want to provide a simple interface to a complex subsystem.

2. The subsystem has become unwieldy with many classes, or when you want to decouple clients from the subsystem's components.

3. You want to layer subsystems and expose a unified API to each layer.

Comments