Lesson 5
Design Patterns in JavaScript: Practical Applications
Lesson Introduction

Hello! Today, we'll venture into the realm of design patterns. Specifically, we'll tackle exercises that apply a single design pattern to problem-solving. Mastering these patterns is a surefire way to extend your coding skills.

Our goal today is to fortify your understanding of when and how to apply specific Object-Oriented Programming (OOP) design patterns. These patterns include Encapsulation, Abstraction, Polymorphism, and Composition.

We'll dissect four real-life scenarios and distinguish which pattern is applicable and why.

Let's get underway!

Real-life Example 1: Database Management System (Encapsulation)

The Encapsulation pattern proves beneficial for the development of a Database Management System (DBMS). Each DBMS table represents a class, the fields represent private data members, and the functions operating on this data serve as methods.

Encapsulation ensures that data members are accessed through methods that promote data integrity and prevent inadvertent anomalies. Here's a mini-code snippet to support this concept:

JavaScript
1class Employees { 2 #employees = {}; // private data member 3 4 addEmployee(eid, name) { // method to operate on private data 5 this.#employees[eid] = name; 6 } 7 8 updateEmployee(eid, newName) { // method to operate on private data 9 if (this.#employees.hasOwnProperty(eid)) { 10 this.#employees[eid] = newName; 11 } 12 } 13} 14 15const employees = new Employees(); 16employees.addEmployee(1, "John"); 17employees.addEmployee(2, "Mark"); 18 19employees.updateEmployee(2, "Jake");

In this context, Encapsulation restricts direct access to employee data, presenting a protective layer via designated methods.

Real-life Example 2: Graphic User Interface (GUI) Development (Polymorphism)

When transitioning to GUI development, consider the creation of controls like buttons or checkboxes. Despite belonging to the same class, each responds differently when clicked. This situation illustrates Polymorphism, which allows us to handle different objects uniformly via a common interface.

Check out this illustrative example:

JavaScript
1class Control { // common base class 2 click() { // method that can be overridden 3 throw new Error("This method should be overridden by subclasses"); 4 } 5} 6 7class Button extends Control { // derived class 8 click() { 9 console.log("Button Clicked!"); // overridden method 10 } 11} 12 13class CheckBox extends Control { // derived class 14 click() { 15 console.log("CheckBox Clicked!"); // overridden method 16 } 17} 18 19// Create objects 20const b = new Button(); 21const c = new CheckBox(); 22 23// Click Controls 24b.click(); // Outputs: Button Clicked! 25c.click(); // Outputs: CheckBox Clicked!

Despite sharing the common click interface, different controls display unique responses. This characteristic demonstrates Polymorphism.

Real-life Example 3: Creating a Web Page Structure (Composition)

Let's explore the Composition design pattern through a JavaScript approach to create a simple web page structure. Here, we'll build a fundamental structure representing a webpage composed of various elements like headers, paragraphs, and lists. This abstraction allows us to understand how composite objects work together to form a larger system.

JavaScript
1class WebPageElement { 2 render() { 3 throw new Error("This method should be overridden by subclasses"); 4 } 5} 6 7class Header extends WebPageElement { 8 constructor(text) { 9 super(); 10 this.text = text; 11 } 12 13 render() { 14 return `<h1>${this.text}</h1>`; 15 } 16} 17 18class Paragraph extends WebPageElement { 19 constructor(text) { 20 super(); 21 this.text = text; 22 } 23 24 render() { 25 return `<p>${this.text}</p>`; 26 } 27} 28 29class List extends WebPageElement { 30 constructor(items) { 31 super(); 32 this.items = items; 33 } 34 35 render() { 36 const itemsStr = this.items.map(item => `<li>${item}</li>`).join("\n"); 37 return `<ul>${itemsStr}</ul>`; 38 } 39} 40 41class WebPage { 42 constructor(title) { 43 this.title = title; 44 this.elements = []; 45 } 46 47 addElement(element) { 48 this.elements.push(element); 49 } 50 51 display() { 52 const elementsStr = this.elements.map(element => element.render()).join("\n"); 53 return `<html>\n<head>\n <title>${this.title}</title>\n</head>\n<body>\n ${elementsStr}\n</body>\n</html>`; 54 } 55} 56 57// Example usage 58const page = new WebPage("My Web Page"); 59page.addElement(new Header("Welcome to My Web Page")); 60page.addElement(new Paragraph("This is a paragraph of text on the web page.")); 61page.addElement(new List(["Item 1", "Item 2", "Item 3"])); 62 63console.log(page.display());

In this code, we've designed a web page structure using the Composition design pattern. Each web page element (Header, Paragraph, and List) is a WebPageElement, allowing for unified handling while maintaining their specific behaviors (rendering as HTML elements).

The WebPage class acts as a composite object that can contain an arbitrary number of WebPageElement instances, each representing different parts of a web page. By adding these elements to the WebPage and invoking the display method, we dynamically compose a complete web page structure in HTML format.

Real-life Example 4: Creating a Vehicle (Abstraction)

Consider creating a Vehicle class in JavaScript. Here, Abstraction comes into play. It allows you to expose only the necessary functionality and abstract away the internal workings of the Vehicle.

Let's see this in code:

JavaScript
1class Vehicle { 2 constructor(color, engineType) { 3 if (new.target === Vehicle) { 4 throw new TypeError("Cannot instantiate an abstract class."); 5 } 6 this.color = color; 7 this.engineType = engineType; 8 this.engineRunning = false; 9 } 10 11 startEngine() { 12 throw new Error("This method should be overridden by subclasses"); 13 } 14 15 stopEngine() { 16 throw new Error("This method should be overridden by subclasses"); 17 } 18 19 drive() { 20 throw new Error("This method should be overridden by subclasses"); 21 } 22} 23 24class Car extends Vehicle { 25 startEngine() { 26 this.engineRunning = true; 27 console.log("Car engine started!"); 28 } 29 30 stopEngine() { 31 this.engineRunning = false; 32 console.log("Car engine stopped!"); 33 } 34 35 drive() { 36 if (this.engineRunning) { 37 console.log("Car is driving!"); 38 } else { 39 console.log("Start the engine first!"); 40 } 41 } 42} 43 44// Example usage 45const car = new Car("red", "gasoline"); 46car.startEngine(); 47car.drive();

Here, the Vehicle class defines the structure and necessary methods such as startEngine(), stopEngine(), and drive(), while throwing errors if they are not overridden. The Car class provides the concrete implementations of these methods. However, it hides or abstracts away internal state management (engineRunning). This is a basic instance of Abstraction, which simplifies the interaction with the class and hides underlying complexity.

Design Pattern Identification

Let's recap the major OOP patterns:

  • Encapsulation: This pattern confines data and related methods into one unit, veiling direct data access.
  • Abstraction: This pattern offers a simplified interface, cloaking complexity.
  • Polymorphism: This pattern facilitates treating different objects as related objects of a common superclass.
  • Composition: This pattern builds elaborate systems by composing closely related objects.

Reflect on these principles and practice applying them to a variety of scenarios to better recognize suitable patterns.

Lesson Summary and Practice

Great job! You've poked and prodded at the practical applications of OOP design patterns. We've explored the use of Encapsulation in Database Management Systems, the pivotal role of Polymorphism in GUI development, the important role of Composition when designing a web page builder, and how Abstraction helps to build a vehicle structure.

Next up are hands-on exercises to reinforce these concepts. Remember, practice is the master key to understanding these concepts. So keep coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.