搜尋
首頁後端開發php教程每個軟體工程師都應該知道的頂級設計模式

Top esign Patterns Every Software Engineer Should Know

PHP,特別是 PHP 中的屬性、枚舉和唯讀屬性等現代功能,非常適合實現設計模式。以下是每個軟體工程師都應該了解的五個基本模式。


1. 單例模式

確保一個類別只有一個實例。

final class Config 
{
    private static ?Config $instance = null;

    private function __construct(public readonly array $settings) {}

    public static function getInstance(): Config 
    {
        return self::$instance ??= new Config(['env' => 'production']);
    }
}

// Usage
$config = Config::getInstance();
echo $config->settings['env']; // Output: production

2. 工廠模式

集中物件建立邏輯。

class DatabaseFactory 
{
    public static function create(string $type): Database 
    {
        return match ($type) {
            'mysql' => new MySQLDatabase(),
            'postgres' => new PostgresDatabase(),
            default => throw new InvalidArgumentException("Unknown database type"),
        };
    }
}

interface Database { public function connect(): void; }
class MySQLDatabase implements Database { public function connect() { echo "MySQL connected"; } }
class PostgresDatabase implements Database { public function connect() { echo "Postgres connected"; } }

// Usage
$db = DatabaseFactory::create('mysql');
$db->connect(); // Output: MySQL connected

3. 觀察者模式

通知多個物件有關狀態變更的資訊。

class Event 
{
    private array $listeners = [];

    public function attach(callable $listener): void { $this->listeners[] = $listener; }
    public function trigger(string $data): void { foreach ($this->listeners as $listener) $listener($data); }
}

// Usage
$event = new Event();
$event->attach(fn($data) => print "Listener 1: $data\n");
$event->attach(fn($data) => print "Listener 2: $data\n");

$event->trigger("Event triggered"); 
// Output:
// Listener 1: Event triggered
// Listener 2: Event triggered

4. 裝飾器模式

動態新增行為給物件。

interface Text { public function render(): string; }

class PlainText implements Text 
{
    public function __construct(private string $text) {}
    public function render(): string { return $this->text; }
}

class BoldText implements Text 
{
    public function __construct(private Text $text) {}
    public function render(): string { return "<b>" . $this->text->render() . "</b>"; }
}

// Usage
$text = new BoldText(new PlainText("Hello, World!"));
echo $text->render(); // Output: <b>Hello, World!</b>

5. 策略模式

運行時在演算法之間切換。

interface PaymentStrategy { public function pay(float $amount): void; }

class CreditCardPayment implements PaymentStrategy 
{
    public function pay(float $amount): void { echo "Paid $amount with Credit Card\n"; }
}

class PayPalPayment implements PaymentStrategy 
{
    public function pay(float $amount): void { echo "Paid $amount via PayPal\n"; }
}

class PaymentProcessor 
{
    public function __construct(private PaymentStrategy $strategy) {}

    public function execute(float $amount): void 
    {
        $this->strategy->pay($amount);
    }
}

// Usage
$processor = new PaymentProcessor(new PayPalPayment());
$processor->execute(100.00); // Output: Paid 100 via PayPal

這些模式解決了現實世界的問題,是編寫可維護和可擴展的應用程式的基礎。

哪種模式與您目前的專案產生共鳴?快來評論裡討論吧! ?

以上是每個軟體工程師都應該知道的頂級設計模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中