欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php策略模式簡單示例分析【區(qū)別于工廠模式】

 更新時間:2019年09月25日 09:31:57   作者:學知無涯  
這篇文章主要介紹了php策略模式,對比工廠模式簡單分析了php策略模式的原理與使用方法,需要的朋友可以參考下

本文實例講述了php策略模式。分享給大家供大家參考,具體如下:

策略模式和工廠模式很像。

工廠模式:著眼于得到對象,并操作對象。

策略模式:著重得到對象某方法的運行結果。

示例:

//實現(xiàn)一個簡單的計算器
interface MathOp{
  public function calculation($num1,$num2);
}
//加法
class MathAdd implements MathOp{
  public function calculation($num1,$num2){
    return $num1 + $num2;
  }
}
//減法
class MathSub implements MathOp{
  public function calculation($num1,$num2){
    return $num1 - $num2;
  }
}
//乘法
class MathMulti implements MathOp{
  public function calculation($num1,$num2){
    return $num1 * $num2;
  }
}
//除法
class MathDiv implements MathOp{
  public function calculation($num1,$num2){
    return $num1 / $num2;
  }
}
class Op{
  protected $op_class = null;
  public function __construct($op_type){
    $this->op_class = 'Math' . $op_type;
  }
  public function get_result($num1,$num2){
    $cls = new $this->op_class;
    return $cls->calculation($num1,$num2);
  }
}
$obj = new Op('Add');
echo $obj->get_result(6,2);//8
$obj = new Op('Sub');
echo $obj->get_result(6,5);//1
$obj = new Op('Multi');
echo $obj->get_result(6,2);//12
$obj = new Op('Div');
echo $obj->get_result(6,2);//3

更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設計有所幫助。

相關文章

最新評論