Applying Factory and Adapter for Smart Home Devices

Applying Factory Method and Adapter Patterns for Smart Home Devices

This course is focused on integrating the design patterns we've studied into a practical project: building a smart home system. Throughout this course, you'll learn how to create and adapt various smart home devices using the Factory Method and Adapter patterns. By the end, you will have a solid understanding of how these design patterns can make your smart home system more efficient, modular, and easier to maintain.

In this unit, we explore two essential design patterns: Factory Method and Adapter. These patterns help us create and adapt devices within a smart home system. To effectively implement these patterns, we will build the devices using the Factory Method and then adapt these devices to interact with other parts of the system using the Adapter pattern.

Quick Summary

  1. Factory Method Pattern:

    • Purpose: Encapsulates the creation of objects, making it easier to introduce new object types without altering existing code.
    • Steps:
      • Define an abstract class (Device).
      • Create specific device classes (Light, Fan) inheriting from the abstract class.
      • Implement a factory class (DeviceFactory) to generate instances of these devices.
  2. Adapter Pattern:

    • Purpose: Makes incompatible interfaces compatible. Allows objects from different classes to work together.
    • Steps:
      • Define an adapter interface (USPlug).
      • Create adapter classes (LightAdapter, FanAdapter) that implement this interface and adapt the devices (Light, Fan) to the required interface.

Let’s move forward and start implementing these patterns.

Defining Smart Home Devices

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

C#
// Abstract Product
abstract class Device
{
    public abstract void TurnOn();
    public abstract void TurnOff();
}

// Concrete Product - Light
class Light : Device
{
    public override void TurnOn() => Console.WriteLine("Light is on.");

    public override void TurnOff() => Console.WriteLine("Light is off.");
}

// Concrete Product - Fan
class Fan : Device
{
    private int speed;

    public override void TurnOn() => Console.WriteLine("Fan is on.");

    public override void TurnOff() => Console.WriteLine("Fan is off.");

    public void SetSpeed(int speed)
    {
        this.speed = speed;
        Console.WriteLine("Fan speed set to " + speed + ".");
    }
}

With our basic devices defined, we can now integrate the Factory Method pattern.

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