您现在的位置是:首页 > PHP PHP的未来

PHP的未来

2025年08月19日 【PHP】 设计模式
简介 用最简洁的 PHP 代码把三种最常用设计模式一次说明白。复制即可运行,也方便你日后当“速查表”。

单例模式

final class Singleton
{
    /**
     * @var Singleton
     */
    private static $instance;

    public static function getInstance(): Singleton
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    private function __construct()
    {
    }

    private function __clone()
    {

    }

    private function __wakeup()
    {

    }
}

$obj = Singleton::getInstance();
var_dump($obj);

观察者模式

interface MessageObserver
{
    public function send($orderId);
}

class SmsObserver implements MessageObserver
{
    public function send($orderId)
    {
        echo "发送订单{$orderId}短信通知" . PHP_EOL;
    }
}

class EmailObserver implements MessageObserver
{
    public function send($orderId)
    {
        echo "发送订单{$orderId}邮件通知" . PHP_EOL;
    }
}

class Order
{
    protected $objects = [];

    protected $id;

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

    public function addObserver(MessageObserver $object)
    {
        $this->objects[] = $object;
    }

    public function notify()
    {
        foreach ($this->objects as $object) {
            $object->send($this->id);
        }
    }
}

$m = new Order(1);
$m->addObserver(new EmailObserver());
$m->addObserver(new SmsObserver());
$m->notify();

装饰器模式

interface MobilePhone
{
    public function getFullName();
}

class Iphone implements MobilePhone
{
    protected $name = 'iPhone';

    public function __construct($model)
    {
        $this->name = $this->name . ' ' . $model;
    }

    public function getFullName()
    {
        return $this->name;
    }
}

abstract class MobilePhoneDecorator implements MobilePhone
{
    /**
     * @var MobilePhone
     */
    protected $mobilePhone;

    public function __construct(MobilePhone $mobilePhone)
    {
        $this->mobilePhone = $mobilePhone;
    }
}

class Color extends MobilePhoneDecorator
{
    protected $color;

    public function __construct(MobilePhone $mobilePhone, $color)
    {
        parent::__construct($mobilePhone);
        $this->color = $color;
    }

    public function getFullName()
    {
        return $this->mobilePhone->getFullName() . ' ' . $this->color;
    }
}

class Memory extends MobilePhoneDecorator
{
    protected $memory;

    public function __construct(MobilePhone $mobilePhone, $memory)
    {
        parent::__construct($mobilePhone);
        $this->memory = $memory;
    }

    public function getFullName()
    {
        return $this->mobilePhone->getFullName() . ' ' . $this->memory;
    }
}

$i = new Iphone('Xs');
$i = new Color($i, '红色');
$i = new Memory($i, '64G');

var_dump($i->getFullName());
很赞哦! (64人围观)