首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 設計模式:適配器模式 實作範例

     編輯:PHP 綜合知識

模式定義

將一個類別的介面轉換成客戶端期望的另一個介面,使原本不相容的類別能夠合作。

應用場景

  • 整合第三方庫,介面不符合系統規範。
  • 舊系統遷移,保留既有類別但需符合新介面。

程式碼實作

<?php
/** 既有舊類別:介面不符合 Cacheable */
class OldCache {
    public function __construct() { echo "OldCache construct
"; } public function store($key, $value) { echo "OldCache store
"; } public function remove($key) { echo "OldCache remove
"; } public function fetch($key) { echo "OldCache fetch
"; } } /** 目標介面 */ interface Cacheable { public function set($key, $value); public function get($key); public function del($key); } /** 適配器:實作目標介面,內部委派給 OldCache */ class OldCacheAdapter implements Cacheable { private $_cache = null; public function __construct() { $this->_cache = new OldCache(); } public function set($key, $value) { return $this->_cache->store($key, $value); } public function get($key) { return $this->_cache->fetch($key); } public function del($key) { return $this->_cache->remove($key); } } /* 使用範例 */ $objCache = new OldCacheAdapter(); $objCache->set('test', 1); $objCache->get('test'); $objCache->del('test');

類別圖說明

  • Target (Cacheable):客戶端期望的介面。
  • Adaptee (OldCache):需被適配的既有類別。
  • Adapter (OldCacheAdapter):實作 Target,持有 Adaptee 實例,轉發呼叫。

優點

  • 符合開放封閉原則:不修改既有類別即可擴展功能。
  • 單一職責:適配邏輯集中在 Adapter,不污染業務代碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved