>  기사  >  백엔드 개발  >  PHP 전략 모드의 코드 공유

PHP 전략 모드의 코드 공유

黄舟
黄舟원래의
2017-03-16 09:25:481217검색

PHP전략 모드 코드 공유

<?php  
// 策略模式  
  
interface Calculator  
{  
    public function calc($a, $b);  
}  
  
/** 
 * add strategy 
 */  
class AddCalculator implements Calculator  
{  
    public function calc($a, $b)  
    {  
        return intval($a) + intval($b);  
    }  
}  
  
/** 
 * multiply stategy 
 */  
class MultiplyCalculator implements Calculator  
{  
    public function calc($a, $b)  
    {  
        return intval($a) * intval($b);  
    }  
}  
  
// -------------------------------------------------------  
  
/** 
 * sample code 
 */  
class StrategySample  
{  
    private $calc;  
  
    public function construct(Calculator $c = NULL)  
    {  
        if(!is_null($c))  
            $this->calc = $c;  
    }  
  
    /** 
     * set calculator 
     */  
    public function setCalculator(Calculator $c)  
    {  
        $this->calc = $c;  
    }  
  
    /** 
     * get calculator 
     */  
    public function getCalculator()  
    {  
        return $this->calc;  
    }  
  
    public function doCalc($a, $b)  
    {  
        return $this->calc->calc($a, $b);  
    }  
}  
  
// test code  
$add = new AddCalculator();  
$strategy = new StrategySample($add);  
echo $strategy->doCalc(2, 3);  
  
echo &#39;<br>&#39;;  
$strategy->setCalculator(new MultiplyCalculator());  
echo $strategy->doCalc(2, 3);

위 내용은 PHP 전략 모드의 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.