Next, we'll develop a shape-drawing application capable of drawing various shapes. For this, we'll employ the principles of Abstraction and Composition.
Abstraction simplifies the complexity associated with drawing different shapes.
Composition takes care of composite shapes.
Here's how we translate these principles into our shape-drawing application:
<?php
// Define the basic Shape class
abstract class Shape {
// Abstract method that will be implemented in each subclass
public abstract function draw();
}
// Define the Circle class
class Circle extends Shape {
// Implement the draw method for circle
public function draw() {
echo "Drawing a circle.\n";
}
}
// Define the Square class
class Square extends Shape {
// Implement the draw method for square
public function draw() {
echo "Drawing a square.\n";
}
}
// Define the ShapeComposite class
class ShapeComposite extends Shape {
// Initialize with an empty array of shapes
private $shapes = [];
// Add a new shape to the composite
public function addShape($shape) {
$this->shapes[] = $shape;
}
// Implement the draw method to draw each shape in the composite
public function draw() {
foreach ($this->shapes as $shape) {
$shape->draw();
}
}
}
$circle = new Circle();
$square = new Square();
// Drawing individual shapes
$circle->draw(); // Output: Drawing a circle.
$square->draw(); // Output: Drawing a square.
// Create a ShapeComposite instance for composite shapes
$compositeShape = new ShapeComposite();
// Add individual shapes to the composite
$compositeShape->addShape($circle);
$compositeShape->addShape($square);
// Drawing the composite shape
$compositeShape->draw();
// Output:
// Drawing a circle.
// Drawing a square.
?>
Abstraction: In this example, the Shape class is abstract. We don’t care about the specific details of how each shape is drawn here, but we know that each shape must have a draw() method. The abstract class helps us define this rule for all shapes.
Composition: The ShapeComposite class demonstrates composition by combining multiple shapes. It can hold and draw multiple shapes together. Composition is used when one object (a composite shape) contains other objects (individual shapes).