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

Step 2: Create Leaf Objects
FileLeaf.php
name = $name;
        $this->size = $size;
    }

    public function getSize() {
        return $this->size;
    }

    public function getName() {
        return $this->name;
    }
}
Step 3: Create Composite Objects DirectoryComposite.php
name = $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.php
add($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

No comments:

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