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/zh-tw/n/331535.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
XBKEN的頭像XBKEN
上一篇 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

發表回復

登錄後才能評論