Lesson 5
Applying Design Patterns in C#: Real-world Examples
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:

C#
1using System; 2using System.Collections.Generic; 3 4public class Employees { 5 private Dictionary<int, string> employees = new Dictionary<int, string>(); // private data member 6 7 public void AddEmployee(int eid, string name) { // method to operate on private data 8 employees[eid] = name; 9 } 10 11 public void UpdateEmployee(int eid, string newName) { // method to operate on private data 12 if (employees.ContainsKey(eid)) { 13 employees[eid] = newName; 14 } 15 } 16 17 public string GetEmployee(int eid) { // getter method for private data 18 return employees.ContainsKey(eid) ? employees[eid] : null; 19 } 20} 21 22public class Program { 23 public static void Main(string[] args) { 24 Employees employees = new Employees(); 25 employees.AddEmployee(1, "John"); 26 employees.AddEmployee(2, "Mark"); 27 28 employees.UpdateEmployee(2, "Jake"); 29 30 Console.WriteLine(employees.GetEmployee(1)); // Outputs: John 31 Console.WriteLine(employees.GetEmployee(2)); // Outputs: Jake 32 } 33}

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:

C#
1using System; 2 3public class Control { 4 public virtual void Click() { 5 // method that can be overridden 6 } 7} 8 9public class Button : Control { 10 public override void Click() { 11 Console.WriteLine("Button Clicked!"); // overridden method 12 } 13} 14 15public class CheckBox : Control { 16 public override void Click() { 17 Console.WriteLine("CheckBox Clicked!"); // overridden method 18 } 19} 20 21public class Program { 22 public static void Main(string[] args) { 23 Control b = new Button(); 24 Control c = new CheckBox(); 25 26 // Click Controls 27 b.Click(); // Outputs: Button Clicked! 28 c.Click(); // Outputs: CheckBox Clicked! 29 } 30}

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 C# 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.

C#
1using System; 2using System.Collections.Generic; 3using System.Text; 4 5public interface IWebPageElement { 6 string Render(); 7} 8 9public class Header : IWebPageElement { 10 private string text; 11 12 public Header(string text) { 13 this.text = text; 14 } 15 16 public string Render() { 17 return $"<h1>{text}</h1>"; 18 } 19} 20 21public class Paragraph : IWebPageElement { 22 private string text; 23 24 public Paragraph(string text) { 25 this.text = text; 26 } 27 28 public string Render() { 29 return $"<p>{text}</p>"; 30 } 31} 32 33public class ListElement : IWebPageElement { 34 private List<string> items; 35 36 public ListElement(List<string> items) { 37 this.items = items; 38 } 39 40 public string Render() { 41 StringBuilder itemsStr = new StringBuilder(); 42 foreach (var item in items) { 43 itemsStr.Append($"<li>{item}</li>"); 44 } 45 return $"<ul>{itemsStr}</ul>"; 46 } 47} 48 49public class WebPage { 50 private string title; 51 private List<IWebPageElement> elements; 52 53 public WebPage(string title) { 54 this.title = title; 55 this.elements = new List<IWebPageElement>(); 56 } 57 58 public void AddElement(IWebPageElement element) { 59 elements.Add(element); 60 } 61 62 public string Display() { 63 StringBuilder elementsStr = new StringBuilder(); 64 foreach (var element in elements) { 65 elementsStr.AppendLine(element.Render()); 66 } 67 return $"<html>\n<head>\n <title>{title}\n</title>\n</head>\n<body>\n {elementsStr}\n</body>\n</html>"; 68 } 69} 70 71public class Program { 72 public static void Main(string[] args) { 73 WebPage page = new WebPage("My Web Page"); 74 page.AddElement(new Header("Welcome to My Web Page")); 75 page.AddElement(new Paragraph("This is a paragraph of text on the web page.")); 76 77 List<string> items = new List<string> { "Item 1", "Item 2", "Item 3" }; 78 page.AddElement(new ListElement(items)); 79 80 Console.WriteLine(page.Display()); 81 /* 82 Outputs: 83 <html> 84 <head> 85 <title>My Web Page 86 </title> 87 </head> 88 <body> 89 <h1>Welcome to My Web Page</h1> 90 <p>This is a paragraph of text on the web page.</p> 91 <ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul> 92 </body> 93 </html> 94 */ 95 } 96}

In this code, we've designed a web page structure using the Composition design pattern. Each web page element (Header, Paragraph, and ListElement) is an IWebPageElement, 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 IWebPageElement 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 C#. Here, Abstraction comes into play. You expose only the necessary functionality and abstract away the internal workings of the Vehicle.

Let's see this in code:

C#
1using System; 2 3public abstract class Vehicle { 4 protected string color; 5 protected string engineType; 6 protected bool engineRunning; 7 8 protected Vehicle(string color, string engineType) { 9 this.color = color; 10 this.engineType = engineType; 11 this.engineRunning = false; 12 } 13 14 public abstract void StartEngine(); 15 public abstract void StopEngine(); 16 public abstract void Drive(); 17} 18 19public class Car : Vehicle { 20 public Car(string color, string engineType) : base(color, engineType) { } 21 22 public override void StartEngine() { 23 engineRunning = true; 24 Console.WriteLine("Car engine started!"); 25 } 26 27 public override void StopEngine() { 28 engineRunning = false; 29 Console.WriteLine("Car engine stopped!"); 30 } 31 32 public override void Drive() { 33 if (engineRunning) { 34 Console.WriteLine($"{color} car is driving on the {engineType} engine type!"); 35 } else { 36 Console.WriteLine("Start the engine first!"); 37 } 38 } 39} 40 41public class Program { 42 public static void Main(string[] args) { 43 Car car = new Car("red", "gasoline"); 44 car.StartEngine(); 45 car.Drive(); 46 /* 47 Output: 48 Car engine started! 49 red car is driving on the gasoline engine type! 50 */ 51 } 52}

Here, the Vehicle abstract class exposes relevant and necessary functions such as StartEngine(), StopEngine(), and Drive(), while the Car class implements this abstract class and provides concrete implementations. 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

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 importance 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.