PHP

设计模式

1.单例模式

<?php 
class Singleton 
{ 
    private static $instance; 
    private function __construct() 
    { 
    } 
    public static function getInstance() 
    { 
        if (!(self::$instance instanceof self)) { 
            self::$instance = new self(); 
        } 
        return self::$instance; 
    } 
} 
?>

2.工厂模式

<?php
class Factory 
{ 
    public static function create($type) 
    { 
        if ($type == 'A') { 
            return new TypeA(); 
        } elseif ($type == 'B') { 
            return new TypeB(); 
        } 
    } 
} 

class TypeA 
{ 
    public function getName() 
    { 
        return 'This is Type A'; 
    } 
} 

class TypeB 
{ 
    public function getName() 
    { 
        return 'This is Type B'; 
    } 
} 

$typeA = Factory::create('A'); 
echo $typeA->getName(); 

$typeB = Factory::create('B'); 
echo $typeB->getName(); 
?>

3.策略模式

<?php
interface Strategy 
{ 
    public function doOperation($num1, $num2); 
} 

class OperationAdd implements Strategy 
{ 
    public function doOperation($num1, $num2) 
    { 
        return $num1 + $num2; 
    } 
} 

class OperationSubstract implements Strategy 
{ 
    public function doOperation($num1, $num2) 
    { 
        return $num1 - $num2; 
    } 
} 

class OperationMultiply implements Strategy 
{ 
    public function doOperation($num1, $num2) 
    { 
        return $num1 * $num2; 
    } 
} 

class Context 
{ 
    private $strategy; 
    public function __construct(Strategy $strategy) 
    { 
        $this->strategy = $strategy; 
    } 
    public function executeStrategy($num1, $num2) 
    { 
        return $this->strategy->doOperation($num1, $num2); 
    } 
} 

$context = new Context(new OperationAdd()); 
echo "10 + 5 = " . $context->executeStrategy(10, 5); 

$context = new Context(new OperationSubstract()); 
echo "10 - 5 = " . $context->executeStrategy(10, 5); 

$context = new Context(new OperationMultiply()); 
echo "10 * 5 = " . $context->executeStrategy(10, 5); 
?>


评论 0

还没有评论,来说两句吧。

验证码

登录后即可评论。评论需要填写验证码。