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.命令模式

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

原创文章,作者:XBKEN,如若转载,请注明出处:https://www.506064.com/n/331535.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
XBKENXBKEN
上一篇 2025-01-20 14:10
下一篇 2025-01-20 14:10

相关推荐

  • 手机安全模式怎么解除?

    安全模式是一种手机自身的保护模式,它会禁用第三方应用程序并使用仅限基本系统功能。但有时候,安全模式会使你无法使用手机上的一些重要功能。如果你想解除手机安全模式,可以尝试以下方法: …

    编程 2025-04-28
  • Qt State Machine与状态机模式

    本文将介绍Qt State Machine和状态机模式在Qt中的实现。Qt提供了QStateMachine和QState两个类,可以方便地实现状态机模式,并且能有效地处理复杂的、多…

    编程 2025-04-27
  • 显示C++设计模式

    本文将详细介绍显示C++设计模式的概念、类型、优点和代码实现。 一、概念 C++设计模式是在软件设计阶段定义,用于处理常见问题的可重用解决方案。这些解决方案是经过测试和验证的,并已…

    编程 2025-04-27
  • Centos7进入单用户模式的解释

    本文将介绍如何在Centos7中进入单用户模式,并从以下几个方面进行详细的阐述。 一、Centos7进入单用户模式的解答 在Centos7中进入单用户模式需要执行以下步骤: 1. …

    编程 2025-04-27
  • Linux sync详解

    一、sync概述 sync是Linux中一个非常重要的命令,它可以将文件系统缓存中的内容,强制写入磁盘中。在执行sync之前,所有的文件系统更新将不会立即写入磁盘,而是先缓存在内存…

    编程 2025-04-25
  • 神经网络代码详解

    神经网络作为一种人工智能技术,被广泛应用于语音识别、图像识别、自然语言处理等领域。而神经网络的模型编写,离不开代码。本文将从多个方面详细阐述神经网络模型编写的代码技术。 一、神经网…

    编程 2025-04-25
  • Java BigDecimal 精度详解

    一、基础概念 Java BigDecimal 是一个用于高精度计算的类。普通的 double 或 float 类型只能精确表示有限的数字,而对于需要高精度计算的场景,BigDeci…

    编程 2025-04-25
  • 详解eclipse设置

    一、安装与基础设置 1、下载eclipse并进行安装。 2、打开eclipse,选择对应的工作空间路径。 File -> Switch Workspace -> [选择…

    编程 2025-04-25
  • Python安装OS库详解

    一、OS简介 OS库是Python标准库的一部分,它提供了跨平台的操作系统功能,使得Python可以进行文件操作、进程管理、环境变量读取等系统级操作。 OS库中包含了大量的文件和目…

    编程 2025-04-25
  • MPU6050工作原理详解

    一、什么是MPU6050 MPU6050是一种六轴惯性传感器,能够同时测量加速度和角速度。它由三个传感器组成:一个三轴加速度计和一个三轴陀螺仪。这个组合提供了非常精细的姿态解算,其…

    编程 2025-04-25

发表回复

登录后才能评论