Sobes.tech
Junior — Middle

Explain the difference between the Decorator and Facade patterns, their purpose, and use cases.

sobes.tech AI

Answer from AI

Decorator and Facade are structural design patterns, but they solve different problems:

  • Decorator allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects. It is used when you need to extend functionality without modifying the original class.

  • Facade provides a simplified interface to a complex system of classes, hiding internal complexity. It is used for ease of working with subsystems.

Example:

  • Decorator: adding logging to an existing object without changing its code.
  • Facade: a single interface for working with multiple services (e.g., network, database, cache).
// Decorator
interface Coffee { fun cost(): Double }
class SimpleCoffee : Coffee { override fun cost() = 2.0 }
class MilkDecorator(val coffee: Coffee) : Coffee {
    override fun cost() = coffee.cost() + 0.5
}

// Facade
class HomeTheaterFacade(val amp: Amplifier, val dvd: DvdPlayer) {
    fun watchMovie() {
        amp.on()
        dvd.play()
    }
}