Understanding Design Patterns
Design patterns are reusable solutions to commonly occurring problems in software design. They offer proven blueprints that can be adapted to various situations, promoting code reusability, maintainability, and efficiency.
Creational Patterns
- Singleton: Ensures a class has only one instance, providing a global access point. Useful for managing resources like database connections or configuration settings.
class Singleton {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
PHP- Factory: Creates objects without specifying their exact class. Used for creating objects based on different criteria.
interface Vehicle {
public function move();
}
class Car implements Vehicle {
public function move() {
echo "Car is moving";
}
}
class Factory {
public static function createVehicle($type) {
switch ($type) {
case 'car':
return new Car();
// ... other vehicle types
default:
throw new Exception("Invalid vehicle type");
}
}
}
PHP- Abstract Factory: Creates families of related objects without specifying their concrete classes.
Structural Patterns
- Adapter: Converts the interface of a class into another interface clients expect.
interface Target {
public function request();
}
class Adaptee {
public function specificRequest() {
// ...
}
}
class Adapter implements Target {
private $adaptee;
public function __construct(Adaptee $adaptee) {
$this->adaptee = $adaptee;
}
public function request() {
$this->adaptee->specificRequest();
}
}
PHP- Decorator: Attaches additional responsibilities to an object dynamically.
abstract class Beverage {
public abstract function cost();
}
class ConcreteBeverage extends Beverage {
public function cost() {
return 10;
}
}
abstract class Decorator extends Beverage {
protected $beverage;
public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
}
class MilkDecorator extends Decorator {
public function cost() {
return $this->beverage->cost() + 2;
}
}
PHPBehavioral Patterns
- Observer: Defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically.
interface Subject {
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
interface Observer {
public function update(Subject $subject);
}
PHPChoosing the Right Pattern
Understanding the problem you’re trying to solve is crucial for selecting the appropriate design pattern. Consider factors like code reusability, flexibility, and maintainability when making your choice.
By effectively applying these design patterns, you can create more robust, scalable, and maintainable PHP applications.