Automating Smart Home Lights with Command and Decorator

Building the Smart Home Automation and Lighting System

As we continue our smart home system project, this unit will focus on two design patterns: the Command pattern and the Decorator pattern. These patterns will help us create a flexible and expandable system for automation and lighting control.

Quick Summary

  1. Basic Setup:

    • Abstract Device: Define an abstract class Device and derive specific device classes (Light, Fan) from it.
    • Factory Method: Implement factory classes to generate instances of these devices.
  2. Command Pattern:

    • Purpose: Encapsulates a request as an object, allowing for parameterization, queuing, logging of requests, and support for undoable operations.
    • Components:
      • Define a ICommand interface and concrete command classes (LightOnCommand, LightOffCommand).
      • Implement a RemoteControl class to execute commands.
  3. Decorator Pattern:

    • Purpose: Adds additional functionalities dynamically to existing objects without altering their structure.
    • Components:
      • Define a decorator class (ColoredLight) to add color functionalities to a Light device.

Let’s move forward and start implementing these patterns.

Defining Smart Home Devices

Before diving into the design patterns, we need to define the devices we'll be working with. We'll start by defining an abstract class Device. Then, create specific device classes Light and Fan that inherit from Device.

C#
// Abstract Product
public abstract class Device
{
    public abstract void On();
    public abstract void Off();
}

// Concrete Device Light
public class Light : Device
{
    public override void On() => Console.WriteLine("Light is on.");
    public override void Off() => Console.WriteLine("Light is off.");
}

// Concrete Device Fan
public class Fan : Device
{
    private int speed;
    public override void On() => Console.WriteLine("Fan is on.");
    public override void Off() => Console.WriteLine("Fan is off.");
    public void SetSpeed(int speed)
    {
        this.speed = speed;
        Console.WriteLine($"Fan speed set to {speed}.");
    }
}

Factory Method for Devices

Next, implement a factory class to generate instances of these devices.

C#
public abstract class DeviceFactory
{
    public abstract Device CreateDevice();
}

public class LightFactory : DeviceFactory
{
    public override Device CreateDevice() => new Light();
}

public class FanFactory : DeviceFactory
{
    public override Device CreateDevice() => new Fan();
}
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