PHP面向对象编程:设计模式全面解析

2024年 5月 10日 40.3k 0

设计模式是可重用的编程解决方案,用于解决常见问题,尤其有利于面向对象编程。创建型:工厂方法(创建对象)、抽象工厂(创建相关对象);结构型:适配器(转换接口)、装饰器(动态添加功能);行为型:观察者(一对多依赖通知)、策略(封装算法,可互换)。

PHP面向对象编程:设计模式全面解析-1

PHP面向对象编程:设计模式全面解析

引言

设计模式是经过反复验证的、可重用的解决方案,用于解决常见编程问题。在面向对象编程(OOP)中,它们有助于编写可维护、可扩展和稳定的代码。本文将探讨PHP中的常见设计模式,并通过实战案例展示其应用。

创建型模式

  • 工厂方法:创建一个对象,而不指定其确切的类。

    interface VehicleFactory {
      public function createVehicle(string $type): Vehicle;
    }
    
    class CarFactory implements VehicleFactory {
      public function createVehicle(string $type): Vehicle {
          return new Car();
      }
    }
    
    $factory = new CarFactory();
    $car = $factory->createVehicle('car');
  • 抽象工厂:提供一个接口,供创建相关或依赖对象家族之用。

    interface ShapeFactory {
      public function createShape(string $type): Shape;
    }
    
    class CircleFactory implements ShapeFactory {
      public function createShape(string $type): Shape {
          return new Circle();
      }
    }
    
    $factory = new CircleFactory();
    $shape = $factory->createShape('circle');

结构型模式

  • 适配器:将一个类的接口转换成另一个期望的接口。

    class OldSystem {
      public function getOldValue(): string {
          return 'old value';
      }
    }
    
    class NewSystem {
      public function getNewValue(): string {
          return 'new value';
      }
    }
    
    class Adapter implements OldSystem {
      private $newSystem;
    
      public function __construct(NewSystem $newSystem) {
          $this->newSystem = $newSystem;
      }
    
      public function getOldValue(): string {
          return $this->newSystem->getNewValue();
      }
    }
    
    $adapter = new Adapter(new NewSystem());
    $value = $adapter->getOldValue();
  • 装饰器:动态地将一个对象的功能添加到另一个对象。

    class Shape {
      public function draw(): void {
          echo 'drawing shape' . PHP_EOL;
      }
    }
    
    class Circle extends Shape {
      public function draw(): void {
          parent::draw();
          echo 'drawing circle' . PHP_EOL;
      }
    }
    
    class ColorDecorator extends Shape {
      private $shape;
      private $color;
    
      public function __construct(Shape $shape, string $color) {
          $this->shape = $shape;
          $this->color = $color;
      }
    
      public function draw(): void {
          $this->shape->draw();
          echo 'drawing ' . $this->color . ' shape' . PHP_EOL;
      }
    }
    
    $shape = new Circle();
    $redShape = new ColorDecorator($shape, 'red');
    $redShape->draw();

行为型模式

  • 观察者:定义对象之间的一种一对多依赖关系,当一个对象发生变化时,所有依赖的对象都会得到通知。

    class Subject {
      private $observers = [];
      private $state;
    
      public function getState(): string {
          return $this->state;
      }
    
      public function setState(string $state): void {
          $this->state = $state;
          $this->notifyObservers();
      }
    
      public function attach(Observer $observer): void {
          $this->observers[] = $observer;
      }
    
      public function detach(Observer $observer): void {
          $index = array_search($observer, $this->observers);
          if ($index !== false) {
              unset($this->observers[$index]);
          }
      }
    
      public function notifyObservers(): void {
          foreach ($this->observers as $observer) {
              $observer->update($this);
          }
      }
    }
    
    class Observer {
      public function update(Subject $subject): void {
          echo 'observer notified, new state: ' . $subject->getState() . PHP_EOL;
      }
    }
    
    $subject = new Subject();
    $observer1 = new Observer();
    $observer2 = new Observer();
    $subject->attach($observer1);
    $subject->attach($observer2);
    $subject->setState('new state');
  • 策略:定义一系列算法,并分别封装它们,使得它们可以互换,独立于使用它们的客户端。

    interface PaymentStrategy {
      public function pay(float $amount): void;
    }
    
    class CreditCardStrategy implements PaymentStrategy {
      public function pay(float $amount): void {
          echo 'paying with credit card: ' . $amount . PHP_EOL;
      }
    }
    
    class PayPalStrategy implements PaymentStrategy {
      public function pay(float $amount): void {
          echo 'paying with PayPal: ' . $amount . PHP_EOL;
      }
    }
    
    class Order {
      private $paymentStrategy;
    
      public function __construct(PaymentStrategy $paymentStrategy) {
          $this->paymentStrategy = $paymentStrategy;
      }
    
      public function pay(float $amount): void {
          $this->paymentStrategy->pay($amount);
      }
    }
    
    $order = new Order(new CreditCardStrategy());
    $order->pay(100);

以上就是PHP面向对象编程:设计模式全面解析的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论