Behavioral patterns
In this section, we will go through the behavioral patterns such as strategy, observer, lazy initialization, and chain of responsibility.
The strategy pattern
The strategy pattern comes in handy where we have multiple chunks of code performing similar operations. It defines an encapsulated and interchangeable family of algorithms. Imagine an order checkout process where we want to implement different shipment providers, such as UPS and FedEx.
The following example demonstrates a possible strategy pattern implementation:
<?php interface ShipmentStrategy { public function calculate($amount); } class UPSShipment implements ShipmentStrategy { public function calculate($amount) { return 'UPSShipment...'; } } class FedExShipment implements ShipmentStrategy { public function calculate($amount) { return 'FedExShipment...'; } } class Checkout { private $amount = 0; public function __construct($amount = 0) { ...