23种设计模式详解

发布时间:2023-05-23

一、创建型模式

创建型模式是用于对象的创建,包括单例模式、工厂模式、抽象工厂模式、建造者模式和原型模式。

1. 单例模式

单例模式是一种保证一个类只有一个实例的模式,实现方法一般是将构造方法私有化,提供一个静态方法返回唯一的实例。

<?php
class Singleton {
    private static $instance;
    private function __construct() {}
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}
?>

2. 工厂模式

工厂模式是一种根据参数创建不同类型的对象的模式,工厂分为简单工厂、工厂方法和抽象工厂三种。

<?php
interface Product {
    public function getName();
}
class ProductA implements Product {
    public function getName() {
        return 'ProductA';
    }
}
class ProductB implements Product {
    public function getName() {
        return 'ProductB';
    }
}
class SimpleFactory {
    public static function createProduct($type) {
        switch ($type) {
            case 'A':
                return new ProductA();
            case 'B':
                return new ProductB();
            default:
                throw new Exception('Invalid type');
        }
    }
}
?>

3. 抽象工厂模式

抽象工厂模式是一种创建一组相关或相互依赖对象的接口,而无需指定它们具体的类。

<?php
interface AbstractFactory {
    public function createProductA();
    public function createProductB();
}
class FactoryA implements AbstractFactory {
    public function createProductA() {
        return new ProductA1();
    }
    public function createProductB() {
        return new ProductB1();
    }
}
class FactoryB implements AbstractFactory {
    public function createProductA() {
        return new ProductA2();
    }
    public function createProductB() {
        return new ProductB2();
    }
}
interface ProductA {
    public function getName();
}
class ProductA1 implements ProductA {
    public function getName() {
        return 'ProductA1';
    }
}
class ProductA2 implements ProductA {
    public function getName() {
        return 'ProductA2';
    }
}
interface ProductB {
    public function getName();
}
class ProductB1 implements ProductB {
    public function getName() {
        return 'ProductB1';
    }
}
class ProductB2 implements ProductB {
    public function getName() {
        return 'ProductB2';
    }
}
?>

4. 建造者模式

建造者模式是一种将对象的创建过程分步骤进行的模式,与工厂模式不同,建造者模式更注重组装对象的过程。

<?php
class Product {
    private $name;
    private $price;
    public function setName($name) {
        $this->name = $name;
        return $this;
    }
    public function setPrice($price) {
        $this->price = $price;
        return $this;
    }
}
class ProductBuilder {
    private $product;
    public function __construct() {
        $this->product = new Product();
    }
    public function build() {
        return $this->product;
    }
    public function setName($name) {
        $this->product->setName($name);
        return $this;
    }
    public function setPrice($price) {
        $this->product->setPrice($price);
        return $this;
    }
}
?>

5. 原型模式

原型模式是一种通过复制现有对象来创建新对象的模式,可以减少对象的创建过程。

<?php
interface Prototype {
    public function clone();
}
class ConcretePrototypeA implements Prototype {
    private $property;
    public function __construct($property) {
        $this->property = $property;
    }
    public function clone() {
        // 返回一个新的ConcretePrototypeA对象,并将属性复制
        return new ConcretePrototypeA($this->property);
    }
}
?>

二、结构型模式

结构型模式指的是用于描述如何组合类和对象以形成更大的结构,包括适配器模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式和代理模式。

1. 适配器模式

适配器模式用于连接两个接口不兼容的对象,本质上是将一个类的接口转换成客户期望的另一个接口。

<?php
interface Target {
    public function request();
}
class Adaptee {
    public function specificRequest() {
        return 'specific request';
    }
}
class Adapter implements Target {
    private $adaptee;
    public function __construct(Adaptee $adaptee) {
        $this->adaptee = $adaptee;
    }
    public function request() {
        return $this->adaptee->specificRequest();
    }
}
?>

2. 桥接模式

桥接模式用于将抽象部分与实现部分分离,以便它们可以独立地变化。

<?php
interface Implementor {
    public function operation();
}
class ConcreteImplementorA implements Implementor {
    public function operation() {
        return 'ConcreteImplementorA operation';
    }
}
class ConcreteImplementorB implements Implementor {
    public function operation() {
        return 'ConcreteImplementorB operation';
    }
}
abstract class Abstraction {
    protected $implementor;
    public function __construct(Implementor $implementor) {
        $this->implementor = $implementor;
    }
    public abstract function operation();
}
class RefinedAbstraction extends Abstraction {
    public function operation() {
        return $this->implementor->operation();
    }
}
?>

3. 组合模式

组合模式用于将对象组合成树形结构以表示“部分-整体”的层次结构,使得客户端可以统一处理单个对象和组合对象。

<?php
abstract class Component {
    protected $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public abstract function add(Component $component);
    public abstract function remove(Component $component);
    public abstract function display();
}
class Leaf extends Component {
    public function add(Component $component) {
        throw new Exception('Cannot add to a leaf');
    }
    public function remove(Component $component) {
        throw new Exception('Cannot remove from a leaf');
    }
    public function display() {
        return "Leaf: {$this->name}";
    }
}
class Composite extends Component {
    private $children = array();
    public function add(Component $component) {
        $this->children[] = $component;
    }
    public function remove(Component $component) {
        foreach ($this->children as $key => $child) {
            if ($child == $component) {
                unset($this->children[$key]);
            }
        }
    }
    public function display() {
        $result = "Composite: {$this->name}\n";
        foreach ($this->children as $child) {
            $result .= $child->display() . "\n";
        }
        return $result;
    }
}
?>

4. 装饰器模式

装饰器模式用于在不更改原始类的情况下,动态地添加功能。

<?php
interface Component {
    public function operation();
}
class ConcreteComponent implements Component {
    public function operation() {
        return 'ConcreteComponent operation';
    }
}
abstract class Decorator implements Component {
    protected $component;
    public function __construct(Component $component) {
        $this->component = $component;
    }
    public function operation() {
        return $this->component->operation();
    }
}
class ConcreteDecoratorA extends Decorator {
    public function operation() {
        return parent::operation() . ' + ConcreteDecoratorA operation';
    }
}
class ConcreteDecoratorB extends Decorator {
    public function operation() {
        return parent::operation() . ' + ConcreteDecoratorB operation';
    }
}
?>

5. 外观模式

外观模式用于为复杂的子系统提供一个简单的接口。

<?php
class SubSystemA {
    public function operationA() {
        return 'SubSystemA operation';
    }
}
class SubSystemB {
    public function operationB() {
        return 'SubSystemB operation';
    }
}
class Facade {
    private $subSystemA;
    private $subSystemB;
    public function __construct(SubSystemA $subSystemA, SubSystemB $subSystemB) {
        $this->subSystemA = $subSystemA;
        $this->subSystemB = $subSystemB;
    }
    public function operation() {
        $resultA = $this->subSystemA->operationA();
        $resultB = $this->subSystemB->operationB();
        return "$resultA + $resultB";
    }
}
?>

6. 享元模式

享元模式用于尽可能减少内存使用和重复对象的创建,通过共享相同的数据来实现这一目标。

<?php
class FlyweightFactory {
    private $flyweights = array();
    public function getFlyweight($key) {
        if (!isset($this->flyweights[$key])) {
            $this->flyweights[$key] = new ConcreteFlyweight($key);
        }
        return $this->flyweights[$key];
    }
}
interface Flyweight {
    public function operation();
}
class ConcreteFlyweight implements Flyweight {
    private $key;
    public function __construct($key) {
        $this->key = $key;
    }
    public function operation() {
        return "ConcreteFlyweight with $this->key";
    }
}
?>

7. 代理模式

代理模式用于提供一个代替对象来控制对它的访问,可以在代理对象中添加额外的控制逻辑。

<?php
interface Subject {
    public function request();
}
class RealSubject implements Subject {
    public function request() {
        return 'RealSubject request';
    }
}
class Proxy implements Subject {
    private $realSubject;
    public function __construct(RealSubject $realSubject) {
        $this->realSubject = $realSubject;
    }
    public function request() {
        // 调用RealSubject的request方法之前或之后可以添加额外的逻辑
        return $this->realSubject->request();
    }
}
?>

三、行为型模式

行为型模式用于描述不同对象之间的通信模式,包括责任链模式、命令模式、解释器模式、迭代器模式、中介者模式、备忘录模式、观察者模式、状态模式、策略模式、模板方法模式和访问者模式。

1. 责任链模式

责任链模式用于在多个对象中传递请求,直到有一个对象处理它为止。

<?php
abstract class Handler {
    protected $successor;
    public function setSuccessor(Handler $successor) {
        $this->successor = $successor;
        return $this;
    }
    public abstract function handleRequest($request);
}
class ConcreteHandler1 extends Handler {
    public function handleRequest($request) {
        if ($request == 'request1') {
            return 'ConcreteHandler1 handled request1';
        } else if ($this->successor) {
            return $this->successor->handleRequest($request);
        }
    }
}
class ConcreteHandler2 extends Handler {
    public function handleRequest($request) {
        if ($request == 'request2') {
            return 'ConcreteHandler2 handled request2';
        } else if ($this->successor) {
            return $this->successor->handleRequest($request);
        }
    }
}
?>

2. 命令模式

命令模式用于封装请求为对象,