简单工厂模式:
<?php abstract class Cash_super { abstract public function accept_cash(float $money); } class Cash_normal extends Cash_super { public function accept_cash(float $money) { return $money; } } class Cash_rebate extends Cash_super { private $_money_rebate; public function __construct(float $money_rebate) { $this->_money_rebate = $money_rebate; } public function accept_cash(float $money) { return $money * $this->_money_rebate; } } class Cash_return extends Cash_super { private $_money_condition = 0; private $_money_return = 0; public function __construct(float $money_condition, float $money_return) { $this->_money_condition = $money_condition; $this->_money_return = $money_return; } public function accept_cash(float $money) { $result = $money; if ($money >= $this->_money_condition) { return $money - floor($money/$this->_money_condition) * $this->_money_return; } return $result; } } class Cash_factory { public static function create_cash_accept($type) : Cash_super { $cs = null; switch ($type) { case ‘normal‘: $cs = new Cash_normal(); break; case ‘300-100‘: $cs = new Cash_return(300, 100); break; case ‘0.8‘: $cs = new Cash_rebate(0.8); break; } return $cs; } } $csuper = Cash_factory::create_cash_accept(‘300-100‘); $total_price = $csuper->accept_cash(30000); echo $total_price;
策略与简单工厂模式的组合:
class Cash_context { private $cs = null; public function __construct($type) { switch ($type) { case ‘normal‘: $this->cs = new Cash_normal(); break; case ‘300-100‘: $this->cs = new Cash_return(300,100); break; case ‘0.8‘: $this->cs = new Cash_rebate(0.8); break; } } public function get_result($money) { return $this->cs->accept_cash($money); } } $cc = new Cash_context(‘300-100‘); $total_price = 0; $total_price = $cc->get_result(5000); echo $total_price;
说明:
简单工厂模式需要让客户端认识两个类。Cash_super和Cash_factory。
策略与简单工厂结合,客户端只需要认识一个类 Cash_context,降低了耦合。
策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法之间的耦合;
时间: 2024-10-25 18:41:03