PHP常用的 五種設計模式及應用場景


設計模式六大原則

開放封閉原則:一個軟件實體如類、模塊和函數應該對擴展開放,對修改關閉。

里氏替換原則:所有引用基類的地方必須能透明地使用其子類的對象.

依賴倒置原則:高層模塊不應該依賴低層模塊,二者都應該依賴其抽象;抽象不應該依賴細節;細節應該依賴抽象。

單一職責原則:不要存在多於一個導致類變更的原因。通俗的說,即一個類只負責一項職責。

接口隔離原則:客戶端不應該依賴它不需要的接口;一個類對另一個類的依賴應該建立在最小的接口上。

迪米特法則:一個對象應該對其他對象保持最少的了解。

 

1.單例設計模式

所謂單例模式,即在應用程序中最多只有該類的一個實例存在,一旦創建,就會一直存在於內存中!

單例設計模式常應用於數據庫類設計,采用單例模式,只連接一次數據庫,防止打開多個數據庫連接。

一個單例類應具備以下特點:

單例類不能直接實例化創建,而是只能由類本身實例化。因此,要獲得這樣的限制效果,構造函數必須標記為private,從而防止類被實例化。

需要一個私有靜態成員變量來保存類實例和公開一個能訪問到實例的公開靜態方法。

在PHP中,為了防止他人對單例類實例克隆,通常還為其提供一個空的私有__clone()方法。

使用場景:只實例化一次,內部實例化,對外只有一個開放方法,只能通過調取該方法進行調取實例化對象。數據庫連接

單例模式的例子:

<?php  

/** 
* Singleton of Database 
*/  
class Database  
{  
  // We need a static private variable to store a Database instance.  
  private static $instance;  

  // Mark as private to prevent it from being instanced.  
  private function__construct()  
  {  
    // Do nothing.  
  }  

  private function__clone()   
  {  
    // Do nothing.  
  }  

  public static function getInstance()   
  {  
    if (!(self::$instance instanceof self)) {  
      self::$instance = new self();  
    }  

    return self::$instance;  
  }  
}  

$a = Database::getInstance();  
$b = Database::getInstance();  

// true  
var_dump($a === $b);  

 

2.工廠設計模式

工廠模式是另一種非常常用的模式,正如其名字所示:確實是對象實例的生產工廠。某些意義上,工廠模式提供了通用的方法有助於我們去獲取對象,而不需要關心其具體的內在的實現

使用場景:使用方法 new實例化類,每次實例化只需調用工廠類中的方法實例化即可。

我們舉例子,假設矩形、圓都有同樣的一個方法,那么我們用基類提供的API來創建實例時,通過傳參數來自動創建對應的類的實例,他們都有獲取周長和面積的功能。

<?php  

interface InterfaceShape   
{  
 function getArea();  
 function getCircumference();  
}  

/** 
* 矩形 
*/  
class Rectangle implements InterfaceShape  
{  
  private $width;  
  private $height;  

  public function __construct($width, $height)  
  {  
    $this->width = $width;  
    $this->height = $height;  
  }  

  public function getArea()   
  {  
    return $this->width* $this->height;  
  }  

  public function getCircumference()  
  {  
    return 2 * $this->width + 2 * $this->height;  
  }  
}  

/** 
* 圓形 
*/  
class Circle implements InterfaceShape  
{  
  private $radius;  

  function __construct($radius)  
  {  
    $this->radius = $radius;  
  }  


  public function getArea()   
  {  
    return M_PI * pow($this->radius, 2);  
  }  

  public function getCircumference()  
  {  
    return 2 * M_PI * $this->radius;  
  }  
}  

/** 
* 形狀工廠類 
*/  
class FactoryShape   
{   
  public static function create()  
  {  
    switch (func_num_args()) {  
      case1:  
      return newCircle(func_get_arg(0));  
      case2:  
      return newRectangle(func_get_arg(0), func_get_arg(1));  
      default:  
        # code...  
        break;  
    }  
  }   
}  

$rect =FactoryShape::create(5, 5);  
// object(Rectangle)#1 (2) { ["width":"Rectangle":private]=> int(5) ["height":"Rectangle":private]=> int(5) }  
var_dump($rect);  
echo "<br>";  

// object(Circle)#2 (1) { ["radius":"Circle":private]=> int(4) }  
$circle =FactoryShape::create(4);  
var_dump($circle);  

 

3.觀察者設計模式

觀察者模式是挺常見的一種設計模式,使用得當會給程序帶來非常大的便利,使用得不當,會給后來人一種難以維護的想法。

什么是觀察者模式?一個對象通過提供方法允許另一個對象即觀察者 注冊自己)使本身變得可觀察。當可觀察的對象更改時,它會將消息發送到已注冊的觀察者。這些觀察者使用該信息執行的操作與可觀察的對象無關。結果是對象可以相互對話,而不必了解原因。觀察者模式是一種事件系統,意味着這一模式允許某個類觀察另一個類的狀態,當被觀察的類狀態發生改變的時候,觀察類可以收到通知並且做出相應的動作;觀察者模式為您提供了避免組件之間緊密耦。看下面例子你就明白了

使用場景:用戶登錄,需要寫日志,送積分,參與活動 等

              使用消息隊列,把用戶和日志,積分,活動之間解耦合

<?php  

/* 
觀察者接口 
*/  
interface InterfaceObserver  
{  
  function onListen($sender, $args);  
  function getObserverName();  
}  

// 可被觀察者接口  
interface InterfaceObservable  
{  
  function addObserver($observer);  
  function removeObserver($observer_name);  
}  

// 觀察者抽象類  
abstract class Observer implements InterfaceObserver  
{  
  protected $observer_name;  

  function getObserverName()   
  {  
    return $this->observer_name;  
  }  

  function onListen($sender, $args)  
  {  

  }  
}  

// 可被觀察類  
abstract class Observable implements InterfaceObservable   
{  
  protected $observers = array();  

  public function addObserver($observer)   
  {  
    if ($observerinstanceofInterfaceObserver)   
    {  
      $this->observers[] = $observer;  
    }  
  }  

  public function removeObserver($observer_name)   
  {  
    foreach ($this->observersas $index => $observer)   
    {  
      if ($observer->getObserverName() === $observer_name)   
      {  
        array_splice($this->observers, $index, 1);  
        return;  
      }  
    }  
  }  
}  

// 模擬一個可以被觀察的類  
class extends Observable   
{  
  public function addListener($listener)   
  {  
    foreach ($this->observersas $observer)   
    {  
      $observer->onListen($this, $listener);  
    }  
  }  
}  

// 模擬一個觀察者類  
class extends Observer   
{  
  protected $observer_name = 'B';  

  public function onListen($sender, $args)   
  {  
    var_dump($sender);  
    echo "<br>";  
    var_dump($args);  
    echo "<br>";  
  }  
}  

// 模擬另外一個觀察者類  
class extends Observer   
{  
  protected $observer_name = 'C';  

  public function onListen($sender, $args)   
  {  
    var_dump($sender);  
    echo "<br>";  
    var_dump($args);  
    echo "<br>";  
  }  
}  

$a = new A();  
// 注入觀察者  
$a->addObserver(new B());  
$a->addObserver(new C());  

// 可以看到觀察到的信息  
$a->addListener('D');  

// 移除觀察者  
$a->removeObserver('B');  

// 打印的信息:  
// object(A)#1 (1) { ["observers":protected]=> array(2) { [0]=> object(B)#2 (1) { ["observer_name":protected]=> string(1) "B" } [1]=> object(C)#3 (1) { ["observer_name":protected]=> string(1) "C" } } }  
// string(1) "D"  
// object(A)#1 (1) { ["observers":protected]=> array(2) { [0]=> object(B)#2 (1) { ["observer_name":protected]=> string(1) "B" } [1]=> object(C)#3 (1) { ["observer_name":protected]=> string(1) "C" } } }  
// string(1) "D"  

 

4.適配器模式

將一個類的接口轉換成客戶希望的另一個接口,適配器模式使得原本的由於接口不兼容而不能一起工作的那些類可以一起工作。
應用場景:老代碼接口不適應新的接口需求,或者代碼很多很亂不便於繼續修改,或者使用第三方類庫。例如:php連接數據庫的方法:mysql,,mysqli,pdo,可以用適配器統一

//老的代碼       

class User {      

    private $name;      

    function __construct($name) {      

        $this->name = $name;      

    }      

    public function getName() {      

        return $this->name;      

    }      

}     
//新代碼,開放平台標准接口      

interface UserInterface {      

    function getUserName();      

}      

class UserInfo implements UserInterface {      

    protected $user;      

    function __construct($user) {      

        $this->user = $user;      

    }      

    public function getUserName() {      

        return $this->user->getName();      

    }      

}     
$olduser = new User('張三');      

echo $olduser->getName()."n";      

$newuser = new UserInfo($olduser);      

echo $newuser->getUserName()."n";      

 

5.策略模式

將一組特定的行為和算法封裝成類,以適應某些特定的上下文環境。

例如:一個電商網站系統,針對男性女性用戶要各自跳轉到不同的商品類目,並且所有廣告位展示不同的廣告

MaleUserStrategy.php

<?php   
namespace IMooc;  
class MaleUserStrategy implements UserStrategy  {  
    function showAd()  
    {  
        echo "IPhone6";  
    }  

    function showCategory()  
    {  
        echo "電子產品";  
    }  
}   

 

FemaleUserStrategy.php

<?php   
namespace IMooc;  
class FemaleUserStrategy implements UserStrategy {  
    function showAd()  
    {  
        echo "2017新款女裝";  
    }  
    function showCategory()  
    {  
        echo "女裝";  
    }  
}   

 

UserStrategy.php

<?php   
namespace IMooc;  
interface UserStrategy {  
    function showAd();  
    function showCategory();  
}     

 

<?php  
interface FlyBehavior{  
    public function fly();  
}  

class FlyWithWings implements FlyBehavior{  
    public function fly(){  
        echo "Fly With Wings \n";  
    }  
}  

class FlyWithNo implements FlyBehavior{  
    public function fly(){  
        echo "Fly With No Wings \n";  
    }  
}  
class Duck{  
    private $_flyBehavior;  
    public function performFly(){  
        $this->_flyBehavior->fly();  
    }  

    public function setFlyBehavior(FlyBehavior $behavior){  
        $this->_flyBehavior = $behavior;  
    }  
}  

class RubberDuck extends Duck{  
}  
// Test Case  
$duck = new RubberDuck();  

/*  想讓鴨子用翅膀飛行 */  
$duck->setFlyBehavior(new FlyWithWings());  
$duck->performFly();              

/*  想讓鴨子不用翅膀飛行 */  
$duck->setFlyBehavior(new FlyWithNo());  
$duck->performFly();      

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM