Info
Open the page on your phone
Tags: #patterns #GoF patterns #structural patterns

Decorator

Decorator - a structural design pattern in object-oriented programming, allowing dynamically adding new functionality or altering the behavior of existing objects without changing their code. This is achieved by creating a new class that wraps the original object and provides it with additional capabilities.

The main components of the decorator include:

* Interface class: Defines the basic interface for components.

* Base class: Implements the core functionality.

* Decorator: Contains a reference to the component and implements the same interface as the component. Adds or modifies the component's functionality.

* Concrete decorator class: Implements specific changes to functionality.

                        
<?php
// Component interface
interface Component {
    public function operation(): string;
}

// Base class
class ConcreteComponent implements Component {
    public function operation(): string {
        return "ConcreteComponent: base operation\n";
    }
}

// Decorator
class Decorator implements Component {
    protected $component;

    public function __construct(Component $component) {
        $this->component = $component;
    }

    public function operation(): string {
        return $this->component->operation();
    }
}

// Concrete decorator
class ConcreteDecoratorA extends Decorator {
    public function operation(): string {
        return "ConcreteDecoratorA(" . parent::operation() . "): additional functionality\n";
    }
}

// Concrete decorator
class ConcreteDecoratorB extends Decorator {
    public function operation(): string {
        return "ConcreteDecoratorB(" . parent::operation() . "): additional functionality\n";
    }
}

// Client code
function clientCode(Component $component) {
    echo "RESULT: " . $component->operation();
}

// Example usage
$simple = new ConcreteComponent();
echo "Client: I can work with the simple component:\n";
clientCode($simple);
echo "\n";

$decorator1 = new ConcreteDecoratorA($simple);
$decorator2 = new ConcreteDecoratorB($decorator1);
echo "Client: Now I can combine decorators:\n";
clientCode($decorator2);
?>