Step 2: Create Leaf Objects FileLeaf.phpname = $name; $this->size = $size; } public function getSize() { return $this->size; } public function getName() { return $this->name; } }Step 3: Create Composite Objects DirectoryComposite.phpname = $name; $this->children = []; } public function add(FileComponent $component) { $this->children[] = $component; } public function getSize() { $totalSize = 0; foreach ($this->children as $child) { $totalSize += $child->getSize(); } return $totalSize; } public function getName() { return $this->name; } }Step 4: Demonstrate the Composite Pattern index.phpadd($file1); $directory->add($file2); // Create a subdirectory and add it to the directory $subdirectory = new DirectoryComposite("Subdirectory"); $subdirectory->add(new FileLeaf("SubFile1.txt", 110)); $directory->add($subdirectory); // Display the size of the directory echo "Total Size of '" . $directory->getName() . "': " . $directory->getSize() . " bytes";Order of Creation
FileComponent.php:
Define the component interface. FileLeaf.php:
Implement the leaf objects. DirectoryComposite.php:
Implement the composite objects. index.php:
Demonstrate the usage of the Composite pattern. Expected Output When you run index.php,
you should see the total size of the directory, which includes the sizes of all files in it and its subdirectories.
The output will be:
Total Size of 'Directory': 630 bytes
Saturday, January 06, 2024
Composite Design Pattern using PHP
Teaching the Composite design pattern in PHP is a great way to introduce students to both advanced object-oriented programming concepts and design patterns. The Composite pattern is particularly useful for treating individual objects and compositions of objects uniformly.
In the Composite pattern, you typically have a component interface, leaf objects, and composite objects. The component interface defines default behavior for all objects, leaf objects perform actual operations, and composite objects store child components (which can be leaf or composite objects).
Let's create a simple example: a file system with directories and files. Directories can contain files or other directories.
Step 1: Define the Component Interface
FileComponent.php
Subscribe to:
Post Comments (Atom)
The Strategy Design Pattern a Behavioral Pattern using C++
The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm's implementation at runtime. Instead of i...
-
The Mediator design pattern is used to centralize complex communications and control between related objects, making it easier to decouple t...
-
The most popular usage of the Mediator pattern in C++ code is facilitating communications between GUI components of an app. The synonym of t...
-
Memento is a behavioral design pattern that allows making snapshots of an object’s state and restoring it in future. The Memento’s principle...
No comments:
Post a Comment