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!
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:
php1<?php 2 3class Employees { 4 private $employees = []; // private data member 5 6 public function addEmployee($eid, $name) { // method to operate on private data 7 $this->employees[$eid] = $name; 8 } 9 10 public function updateEmployee($eid, $newName) { // method to operate on private data 11 if (array_key_exists($eid, $this->employees)) { 12 $this->employees[$eid] = $newName; 13 } 14 } 15 16 public function getEmployee($eid) { // getter method for private data 17 return array_key_exists($eid, $this->employees) ? $this->employees[$eid] : null; 18 } 19} 20 21$employees = new Employees(); 22$employees->addEmployee(1, "John"); 23$employees->addEmployee(2, "Mark"); 24 25$employees->updateEmployee(2, "Jake"); 26 27echo $employees->getEmployee(1); // Outputs: John 28echo "\n"; 29echo $employees->getEmployee(2); // Outputs: Jake 30?>
In this context, Encapsulation
restricts direct access to employee data, presenting a protective layer via designated methods.
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:
php1<?php 2 3abstract class Control { 4 public function click() { 5 // method that can be overridden 6 } 7} 8 9class Button extends Control { 10 public function click() { 11 echo "Button Clicked!\n"; // overridden method 12 } 13} 14 15class CheckBox extends Control { 16 public function click() { 17 echo "CheckBox Clicked!\n"; // overridden method 18 } 19} 20 21$b = new Button(); 22$c = new CheckBox(); 23 24// Click Controls 25$b->click(); // Outputs: Button Clicked! 26$c->click(); // Outputs: CheckBox Clicked! 27?>
Despite sharing the common click
interface, different controls display unique responses. This characteristic demonstrates Polymorphism
.
Let's explore the Composition
design pattern through a PHP approach to creating 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.
php1<?php 2 3interface IWebPageElement { 4 public function render(); 5} 6 7class Header implements IWebPageElement { 8 private $text; 9 10 public function __construct($text) { 11 $this->text = $text; 12 } 13 14 public function render() { 15 return "<h1>{$this->text}</h1>"; 16 } 17} 18 19class Paragraph implements IWebPageElement { 20 private $text; 21 22 public function __construct($text) { 23 $this->text = $text; 24 } 25 26 public function render() { 27 return "<p>{$this->text}</p>"; 28 } 29} 30 31class ListElement implements IWebPageElement { 32 private $items; 33 34 public function __construct($items) { 35 $this->items = $items; 36 } 37 38 public function render() { 39 $itemsStr = ""; 40 foreach ($this->items as $item) { 41 $itemsStr .= "<li>{$item}</li>"; 42 } 43 return "<ul>{$itemsStr}</ul>"; 44 } 45} 46 47class WebPage { 48 private $title; 49 private $elements = []; 50 51 public function __construct($title) { 52 $this->title = $title; 53 } 54 55 public function addElement(IWebPageElement $element) { 56 $this->elements[] = $element; 57 } 58 59 public function display() { 60 $elementsStr = ""; 61 foreach ($this->elements as $element) { 62 $elementsStr .= $element->render() . "\n"; 63 } 64 return "<html>\n<head>\n <title>{$this->title}\n</title>\n</head>\n<body>\n {$elementsStr}\n</body>\n</html>"; 65 } 66} 67 68$page = new WebPage("My Web Page"); 69$page->addElement(new Header("Welcome to My Web Page")); 70$page->addElement(new Paragraph("This is a paragraph of text on the web page.")); 71 72$items = ["Item 1", "Item 2", "Item 3"]; 73$page->addElement(new ListElement($items)); 74 75echo $page->display(); 76?>
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.
Consider creating a Vehicle
class in PHP. 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:
php1<?php 2 3abstract class Vehicle { 4 protected $color; 5 protected $engineType; 6 protected $engineRunning; 7 8 protected function __construct($color, $engineType) { 9 $this->color = $color; 10 $this->engineType = $engineType; 11 $this->engineRunning = false; 12 } 13 14 public abstract function startEngine(); 15 public abstract function stopEngine(); 16 public abstract function drive(); 17} 18 19class Car extends Vehicle { 20 public function __construct($color, $engineType) { 21 parent::__construct($color, $engineType); 22 } 23 24 public function startEngine() { 25 $this->engineRunning = true; 26 echo "Car engine started!\n"; 27 } 28 29 public function stopEngine() { 30 $this->engineRunning = false; 31 echo "Car engine stopped!\n"; 32 } 33 34 public function drive() { 35 if ($this->engineRunning) { 36 echo "{$this->color} car is driving on the {$this->engineType} engine type!\n"; 37 } else { 38 echo "Start the engine first!\n"; 39 } 40 } 41} 42 43$car = new Car("red", "gasoline"); 44$car->startEngine(); 45$car->drive(); 46?>
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 interaction with the class and hides underlying complexity.
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.
Great job! You've explored 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!