PHP常用设计模式汇总

装饰模式:

<?php
abstract class Tile {
  abstract function getWealthFactor();
}
class Plains extends Tile {
  private $wealthfactor = 2;
  function getWealthFactor() {
    return $this->wealthfactor;
  }
}
abstract class TileDecorator extends Tile { // 装饰
  protected $tile;
  function __construct( Tile $tile ) {
    $this->tile = $tile;
  }
}
class DiamondDecorator extends TileDecorator { // 钻石装饰
  function getWealthFactor() {
    return $this->tile->getWealthFactor()+2;
  }
}
class PollutionDecorator extends TileDecorator { // 污染装饰
  function getWealthFactor() {
    return $this->tile->getWealthFactor()-4;
  }
}
$tile = new Plains();
print $tile->getWealthFactor(); // 2
$tile = new DiamondDecorator( new Plains());
print $tile->getWealthFactor(); // 4
$tile = new PollutionDecorator( new DiamondDecorator( new Plains()));
print $tile->getWealthFactor(); // 0
?>

 组合模式:

<?php
abstract class Unit {
  abstract function bombardStrength();
}
class Archer extends Unit {
  function bombardStrength() {
    return 4;
  }
}
class LaserCannonUnit extends Unit {
  function bombardStrength() {
    return 44;
  }
}
class Army {
  private $units = array();
  private $armies= array();
  function addUnit( Unit $unit ) {
    array_push( $this->units, $unit );
  }
  function addArmy( Army $army ) {
    array_push( $this->armies, $army );
  }
  function bombardStrength() {
    $ret = 0;
    foreach( $this->units as $unit ) {
      $ret += $unit->bombardStrength();
    }
    foreach( $this->armies as $army ) {
      $ret += $army->bombardStrength();
    }
    return $ret;
  }
}
$unit1 = new Archer();
$unit2 = new LaserCannonUnit();
$army = new Army();
$army->addUnit( $unit1 );
$army->addUnit( $unit2 );
print $army->bombardStrength();
print "\n";
$army2 = clone $army; // 克隆军队
$army->addArmy( $army2 );
print $army->bombardStrength();
print "\n";
?>

 工厂模式

 <?php
     /**
      * 操作类
      * 因为包含有抽象方法,所以类必须声明为抽象类
      */
     abstract class Operation{
         //抽象方法不能包含函数体
         abstract public function getValue($num1,$num2);//强烈要求子类必须实现该功能函数
     }
     /**
      * 加法类
      */
     class OperationAdd extends Operation {
         public function getValue($num1,$num2){
             return $num1+$num2;
         }
     }
     /**
      * 减法类
      */
     class OperationSub extends Operation {
         public function getValue($num1,$num2){
             return $num1-$num2;
         }
     }
     /**
      * 乘法类
      */
     class OperationMul extends Operation {
         public function getValue($num1,$num2){
             return $num1*$num2;
         }
     }
     /**
      * 除法类
      */
     class OperationDiv extends Operation {
         public function getValue($num1,$num2){
             try {
                 if ($num2==0){
                     throw new Exception("除数不能为0");
                 }else {
                     return $num1/$num2;
                 }
             }catch (Exception $e){
                 echo "错误信息:".$e->getMessage();
             }
         }


    /**
     * 工厂类,主要用来创建对象
     * 功能:根据输入的运算符号,工厂就能实例化出合适的对象
     *
     */
    class Factory{
        public static function createObj($operate){
            switch ($operate){
                case '+':
                    return new OperationAdd();
                    break;
                case '-':
                    return new OperationSub();
                    break;
                case '*':
                    return new OperationSub();
                    break;
                case '/':
                    return new OperationDiv();
                    break;
            }
        }
    }
    $test=Factory::createObj('/');
    $result=$test->getValue(23,0);
    echo $result;
?>

 单例模式

<?php  
    
/** 
* Singleton of Database 
*/  
class Database  
{  
  // We need a static private variable to store a Database instance.  
  privatestatic $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::$instanceinstanceofself)) {  
      self::$instance = newself();  
    }  
    
    returnself::$instance;  
  }  
}  
    
$a =Database::getInstance();  
$b =Database::getInstance();  
    
// true  
var_dump($a === $b);  

 策略模式

<?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();

?>

 适配器模式

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";    

 

posted @ 2017-05-31 16:49  leayrainy  阅读(251)  评论(0编辑  收藏  举报