Introduction

Welcome to the third lesson of our "Applying Design Patterns for Real World Problems using Scala" course! In this lesson, we'll delve into two powerful design patterns: the Command pattern and the Decorator pattern. These patterns will empower you to design a robust and flexible smart home automation and lighting control system in Scala 3. Let's embark on this journey to create a system that’s as adaptable as it is efficient! 🚀

Lesson overview

Here's a brief overview of what we'll be doing in this lesson:

  1. Basic Setup:

    • Abstract Device: Define a trait Device and create specific device classes (Light, Fan) that extend from it.
    • Factory Method: Leverage companion objects to serve as factories for generating instances of these devices.
  2. Command Pattern:

    • Purpose: Encapsulates a request as an object, facilitating parameterization, queuing, logging, and support for undoable operations.
    • Components:
      • Define a Command trait and concrete command classes (LightOnCommand, LightOffCommand).
      • Implement a RemoteControl class for command executions.
  3. Decorator Pattern:

    • Purpose: Dynamically adds functionalities to existing objects without altering their structure.
    • Components:
      • Use a decorator class (ColoredLight) to add color capabilities to a Light device.

Let’s dive into the Scala code and bring these patterns to life! 🎉

Defining Smart Home Devices

Let's start by defining the devices we'll be working with. We'll create a trait Device and extend it with concrete device classes Light and Fan.

// Abstract Device
trait Device:
  def on(): Unit
  def off(): Unit

// Concrete Device: Light
class Light extends Device:
  def on(): Unit = println("Light is on.")
  def off(): Unit = println("Light is off.")

// Concrete Device: Fan
class Fan extends Device:
  private var speed: Int = 0
  def on(): Unit = println("Fan is on.")
  def off(): Unit = println("Fan is off.")
  def setSpeed(speed: Int): Unit =
    this.speed = speed
    println(s"Fan speed set to $speed.")

This code defines the foundational elements of our smart home system:

  • The Device trait establishes a common interface with on() and off() methods.
  • The Light class extends Device with basic functionality to turn the light on and off.
  • The Fan class extends Device and adds the ability to set the fan's speed through the setSpeed() method.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal