使用了策略模式并没有避免添加else{}代码啊
只是添加else{}的地方不一样,有什么区别吗?
只是添加else{}的地方不一样,有什么区别吗?
2019-08-24
使用枚举,表格驱动的方法优化if...else...代码 粗糙写法如下,代码其实还可以优化 class AdvertisingRoleEnum{ const MALE = 1; const FEMALE = 0; public static function getStrategy($gender){ $listExplain[self::MALE] = new \IMooc\MaleUserStrategy(); $listExplain[self::FEMALE] = new \IMooc\FemaleUserStrategy(); return $listExplain[$gender]; } } class Page { protected $strategy; function index() { echo "AD:"; $this->strategy->showAd(); echo "<br/>"; echo "Category:"; $this->strategy->showCategory(); echo "<br/>"; } function setStrategy(\IMooc\UserStrategy $strategy){ $this->strategy = $strategy; } } $page = new Page(); $gender = isset($_GET['female'])??0; $strategy = AdvertisingRoleEnum::getStrategy($gender); //if (isset($_GET['female'])){ // $strategy = new \IMooc\FemaleUserStrategy(); //}else{ // $strategy = new MaleUserStrategy(); //} $page->setStrategy($strategy); $page->index();
举报