Bootstrap

PHP设计模式


前言

设计模式是解决特定问题的通用方案,它们可以提高代码的可维护性、可扩展性和可重用性。


1. 单例模式 (Singleton)

概念: 确保一个类只有一个实例,并提供全局访问点

class Singleton {
    private static $instance;

    private function __construct() {} // 私有构造函数

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

// 使用
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

var_dump($instance1 === $instance2); // 输出: bool(true)

2. 工厂模式 (Factory)

概念: 定义一个接口用于创建对象,但让子类决定实例化哪一个类,工厂模式将对象的实例化推迟到子类

interface Product {
    public function getName();
}

class ConcreteProductA implements Product {
    public function getName() {
        return "Product A";
    }
}

class ConcreteProductB implements Product {
    public function getName() {
        return "Product B";
    }
}

class Factory {
    public static function create($type) {
        switch ($type) {
            case 'A':
                return new ConcreteProductA();
            case 'B':
                return new ConcreteProductB();
            default:
                throw new Exception("Invalid product type.");
        }
    }
}

// 使用
$productA = Factory::create('A');
echo $productA->getName(); // 输出: Product A

3. 观察者模式 (Observer)

定义一种一对多的依赖关系,使得当一个对象状态变化时,所有依赖于它的对象都得到通知并自动更新

class Subject {
    private $observers = [];

    public function attach($observer) {
        $this->observers[] = $observer;
    }

    public function notify() {
        foreach ($this->observers as $observer) {
            $observer->update();
        }
    }

    public function changeState() {
        // 状态变化逻辑
        $this->notify();
    }
}

class Observer {
    public function update() {
        echo "Observer notified.\n";
    }
}

// 使用
$subject = new Subject();
$observer = new Observer();
$subject->attach($observer);

$subject->changeState(); // 输出: Observer notified.

4. 策略模式 (Strategy)

概念: 定义一系列算法,将每一个算法封装起来,并使它们可以互换,策略模式让算法的变化独立于使用算法的客户端

interface Strategy {
    public function execute($a, $b);
}

class ConcreteStrategyAdd implements Strategy {
    public function execute($a, $b) {
        return $a + $b;
    }
}

class ConcreteStrategySubtract implements Strategy {
    public function execute($a, $b) {
        return $a - $b;
    }
}

class Context {
    private $strategy;

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

    public function executeStrategy($a, $b) {
        return $this->strategy->execute($a, $b);
    }
}

// 使用
$context = new Context(new ConcreteStrategyAdd());
echo $context->executeStrategy(5, 3); // 输出: 8

$context = new Context(new ConcreteStrategySubtract());
echo $context->executeStrategy(5, 3); // 输出: 2

5. 命令模式 (Command)

概念: 将请求封装为对象,从而使您能够参数化客户端以使用不同的请求、队列或日志请求,支持可撤销操作

interface Command {
    public function execute();
}

class Light {
    public function turnOn() {
        echo "Light is ON\n";
    }
    public function turnOff() {
        echo "Light is OFF\n";
    }
}

class LightOnCommand implements Command {
    private $light;

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

    public function execute() {
        $this->light->turnOn();
    }
}

class LightOffCommand implements Command {
    private $light;

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

    public function execute() {
        $this->light->turnOff();
    }
}

class RemoteControl {
    private $command;

    public function setCommand(Command $command) {
        $this->command = $command;
    }

    public function pressButton() {
        $this->command->execute();
    }
}

// 使用
$light = new Light();
$lightOn = new LightOnCommand($light);
$lightOff = new LightOffCommand($light);

$remote = new RemoteControl();
$remote->setCommand($lightOn);
$remote->pressButton(); // 输出: Light is ON

$remote->setCommand($lightOff);
$remote->pressButton(); // 输出: Light is OFF

6. 适配器模式 (Adapter)

概念: 将一个类的接口转换成客户端所期望的另一种接口,使得原本由于接口不兼容而无法一起工作的类能够一起工作

class OldSystem {
    public function oldMethod() {
        return "Old System Method\n";
    }
}

interface NewSystemInterface {
    public function newMethod();
}

class Adapter implements NewSystemInterface {
    private $oldSystem;

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

    public function newMethod() {
        return $this->oldSystem->oldMethod();
    }
}

// 使用
$oldSystem = new OldSystem();
$adapter = new Adapter($oldSystem);
echo $adapter->newMethod(); // 输出: Old System Method

7. 装饰者模式 (Decorator)

概念: 动态地给一个对象添加一些额外的职责。使用装饰者模式,用户可以在不改变对象结构的情况下,增加对象的功能

interface Coffee {
    public function cost();
}

class SimpleCoffee implements Coffee {
    public function cost() {
        return 5;
    }
}

class MilkDecorator implements Coffee {
    protected $coffee;

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

    public function cost() {
        return $this->coffee->cost() + 1; // 加上牛奶的费用
    }
}

// 使用
$coffee = new SimpleCoffee();
echo $coffee->cost(); // 输出: 5

$milkCoffee = new MilkDecorator($coffee);
echo $milkCoffee->cost(); // 输出: 6

8. 责任链模式 (Chain of Responsibility)

概念: 使多个对象有机会处理请求,避免请求的发送者与接收者之间的耦合关系,将请求沿着处理链传递,直到有一个对象处理它为止

abstract class Handler {
    protected $nextHandler;

    public function setNext(Handler $handler) {
        $this->nextHandler = $handler;
        return $handler;
    }

    public function handle($request) {
        if ($this->nextHandler) {
            return $this->nextHandler->handle($request);
        }
        return null;
    }
}

class ConcreteHandlerA extends Handler {
    public function handle($request) {
        if ($request === 'A') {
            return "Handled by Handler A";
        }
        return parent::handle($request);
    }
}

class ConcreteHandlerB extends Handler {
    public function handle($request) {
        if ($request === 'B') {
            return "Handled by Handler B";
        }
        return parent::handle($request);
    }
}

// 使用
$handlerA = new ConcreteHandlerA();
$handlerB = new ConcreteHandlerB();
$handlerA->setNext($handlerB);

echo $handlerA->handle('A'); // 输出: Handled by Handler A
echo $handlerA->handle('B'); // 输出: Handled by Handler B

9. 访问者模式 (Visitor)

概念: 封装一些作用于某种数据结构中的各元素的操作,它可以在不改变元素类的前提下,定义新的操作

interface Visitor {
    public function visitBook(Book $book);
    public function visitCD(CD $cd);
}

class Book {
    public function accept(Visitor $visitor) {
        $visitor->visitBook($this);
    }
}

class CD {
    public function accept(Visitor $visitor) {
        $visitor->visitCD($this);
    }
}

class ConcreteVisitor implements Visitor {
    public function visitBook(Book $book) {
        echo "Visiting Book\n";
    }

    public function visitCD(CD $cd) {
        echo "Visiting CD\n";
    }
}

// 使用
$book = new Book();
$cd = new CD();
$visitor = new ConcreteVisitor();

$book->accept($visitor); // 输出: Visiting Book
$cd->accept($visitor);   // 输出: Visiting CD

10. 中介者模式 (Mediator)

概念: 定义一个中介对象,用于封装一组对象之间的交互,使各个对象不需要显式地相互引用,从而降低了耦合度

class Mediator {
    protected $colleagues = [];

    public function addColleague($colleague) {
        $this->colleagues[] = $colleague;
    }

    public function notify($sender, $event) {
        // 处理通知
    }
}

class Colleague {
    protected $mediator;

    public function __construct(Mediator $mediator) {
        $this->mediator = $mediator;
        $mediator->addColleague($this);
    }

    public function doSomething() {
        $this->mediator->notify($this, "something done");
    }
}

// 使用
$mediator = new Mediator();
$colleague = new Colleague($mediator);
$colleague->doSomething();

11. 备忘录模式 (Memento)

概念: 在不违反封装性的前提下,捕获一个对象的内部状态,并在需要时恢复对象的状态

class Memento {
    private $state;

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

    public function getState() {
        return $this->state;
    }
}

class Originator {
    private $state;

    public function setState($state) {
        $this->state = $state;
    }

    public function save() {
        return new Memento($this->state);
    }

    public function restore(Memento $memento) {
        $this->state = $memento->getState();
    }
}

// 使用
$originator = new Originator();
$originator->setState("State1");
$memento = $originator->save();

$originator->setState("State2");
$originator->restore($memento); // 恢复为 State1

12. 迭代器模式 (Iterator)

概念: 提供一种方法顺序访问一个集合对象中的各个元素,而不暴露该对象的内部表示

class MyCollection implements Iterator {
    private $items = [];
    private $current = 0;

    public function add($item) {
        $this->items[] = $item;
    }

    public function current() {
        return $this->items[$this->current];
    }

    public function key() {
        return $this->current;
    }

    public function next() {
        ++$this->current;
    }

    public function rewind() {
        $this->current = 0;
    }

    public function valid() {
        return isset($this->items[$this->current]);
    }
}

// 使用
$collection = new MyCollection();
$collection->add("Item 1");
$collection->add("Item 2");

foreach ($collection as $item) {
    echo $item . "\n"; // 输出: Item 1\n Item 2
}

总结

设计模式能帮助我们在开发应用时更好地组织代码和结构,提升代码的可读性和可维护性,我们可以根据具体需求选择合适的设计模式进行实现

;