Factory and Adapter Patterns
Applying Factory Method and Adapter Patterns for Smart Home Devices
This course focuses 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 implement these patterns effectively, 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
-
Factory Method Pattern:
- Purpose: Encapsulates the creation of objects, making it easier to introduce new object types without altering existing code.
- Steps:
- Define a base class (
Device) using TypeScript'sabstract class. - Create specific device classes (
Light,Fan) that extend from the base class. - Implement a factory class (
DeviceFactory) to generate instances of these devices, using type annotations for safety.
- Define a base class (
-
Adapter Pattern:
- Purpose: Makes incompatible interfaces compatible, allowing objects from different classes to work together.
- Steps:
- Define an adapter interface (
USPlugInterface) using a TypeScriptinterface. - Create adapter classes (
LightAdapter,FanAdapter) that implement this interface and adapt the devices (Light,Fan) to the required interface.
- Define an adapter interface (
Creating Devices with Factory Method Pattern
To begin with, we use the Factory Method pattern in TypeScript to define an abstract base class for our devices, derive specific device classes from this base class, and finally create a factory class responsible for generating instances of these device classes. TypeScript's type annotations and abstract classes help ensure type safety and clear contracts for subclasses.
Code Implementation
Here is the complete code for implementing the Factory Method pattern in TypeScript:
In this TypeScript implementation, the Device class is declared as abstract, enforcing that subclasses must implement the operate method. The DeviceFactory uses a union type ("light" | "fan") for the deviceType parameter, ensuring only valid device types can be passed. Type annotations throughout the code provide compile-time safety and clarity.
