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:
TypeScript
class Employees { private employees: { [key: number]: string } = {}; // private data member with type annotation addEmployee(eid: number, name: string): void { // method to operate on private data this.employees[eid] = name; } updateEmployee(eid: number, newName: string): void { // method to operate on private data if (this.employees.hasOwnProperty(eid)) { this.employees[eid] = newName; } }}const employees = new Employees();employees.addEmployee(1, "John");employees.addEmployee(2, "Mark");employees.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:
TypeScript
abstract class Control { // common base class abstract click(): void; // abstract method to be overridden}class Button extends Control { // derived class click(): void { console.log("Button Clicked!"); // overridden method }}class CheckBox extends Control { // derived class click(): void { console.log("CheckBox Clicked!"); // overridden method }}// Create objectsconst b = new Button();const c = new CheckBox();// Click Controlsb.click(); // Outputs: Button Clicked!c.click(); // Outputs: CheckBox Clicked!
Despite sharing the common click interface, different controls display unique responses. This characteristic demonstrates Polymorphism.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Real-life Example 3: Creating a Web Page Structure (Composition)
Real-life Example 4: Creating a Vehicle (Abstraction)
Consider creating a Vehicle class in TypeScript. 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:
abstract class Vehicle { protected engineRunning: boolean = false; // Property with type annotation constructor(private color: string, private engineType: string) { // Type annotations for parameters } abstract startEngine(): void; // Abstract method with return type abstract stopEngine(): void; // Abstract method with return type abstract drive(): void; // Abstract method with return type}class Car extends Vehicle { startEngine(): void { this.engineRunning = true; console.log("Car engine started!"); } stopEngine(): void { this.engineRunning = false; console.log("Car engine stopped!"); } drive(): void { if (this.engineRunning) { console.log("Car is driving!"); } else { console.log("Start the engine first!"); } }}// Example usageconst car = new Car("red", "gasoline");car.startEngine();car.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!
Let's explore the Composition design pattern through a TypeScript 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.
TypeScript
abstract class WebPageElement { abstract render(): string; // Return type annotation}class Header extends WebPageElement { constructor(private text: string) { // Type annotation for parameter super(); } render(): string { return `<h1>${this.text}</h1>`; }}class Paragraph extends WebPageElement { constructor(private text: string) { // Type annotation for parameter super(); } render(): string { return `<p>${this.text}</p>`; }}class List extends WebPageElement { constructor(private items: string[]) { // Type annotation for parameter super(); } render(): string { const itemsStr = this.items.map(item => `<li>${item}</li>`).join("\n"); return `<ul>${itemsStr}</ul>`; }}class WebPage { private elements: WebPageElement[] = []; // Type annotation for array constructor(private title: string) { // Type annotation for parameter } addElement(element: WebPageElement): void { // Type annotation for parameter this.elements.push(element); } display(): string { // Return type annotation const elementsStr = this.elements.map(element => element.render()).join("\n"); return `<html>\n<head>\n <title>${this.title}</title>\n</head>\n<body>\n ${elementsStr}\n</body>\n</html>`; }}// Example usageconst page = new WebPage("My Web Page");page.addElement(new Header("Welcome to My Web Page"));page.addElement(new Paragraph("This is a paragraph of text on the web page."));page.addElement(new List(["Item 1", "Item 2", "Item 3"]));console.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.
TypeScript
abstract class Vehicle { protected engineRunning: boolean = false; // Property with type annotation constructor(private color: string, private engineType: string) { // Type annotations for parameters } abstract startEngine(): void; // Abstract method with return type abstract stopEngine(): void; // Abstract method with return type abstract drive(): void; // Abstract method with return type}class Car extends Vehicle { startEngine(): void { this.engineRunning = true; console.log("Car engine started!"); } stopEngine(): void { this.engineRunning = false; console.log("Car engine stopped!"); } drive(): void { if (this.engineRunning) { console.log("Car is driving!"); } else { console.log("Start the engine first!"); } }}// Example usageconst car = new Car("red", "gasoline");car.startEngine();car.drive();