您的位置:首页 > 其它

组合模式设计购物车价格计算实例(仅供学习使用)

2014-09-21 13:29 537 查看
组合模式:将一组对象组合为可像单个对像一样被使用的结构
<?php
/**
*组合模式设计购物车价格计算
*
*/
abstract class prices
{
public $price_info = array();

abstract function add(Prices $prices);
abstract function remove(Prices $price);
abstract function show();
}

class price extends prices
{
function __construct($price_info){
$this->price_info= $price_info;
}

public function getName(){
return $this->price_info['name'];
}

public function getPrice(){
return $this->price_info['price'];
}

public function add(Prices $prices){
return false;
}

public function remove(Prices $prices){
return false;
}

public function show(){
echo $this->getName()."____".$this->getPrice();
}
}

class total_price extends prices
{
public $total_price = array();

function __construct($name){
$this->name = $name;
}

public function getName(){
return $this->name;
}

public function add(Prices $price_info){
$this->total_price[] = $price_info;
}

public function getTotal(){
$total = 0;
foreach ($this->total_price as $v){
$total = $total + $v->getPrice();
}
return $total;
}

public function remove(Prices $good_info){
foreach ($this->total_price as $v){
if (json_encode($v) == json_encode($good_info)) {
unset($this->total_price);
}
}
}

public function show(){
echo $this->getName."_____".$this->getTotal()."\n";
foreach ($this->total_price as $v) {
echo $v->show()."\n";
}
}
}

class test
{
public function run(){
$total_prices = new total_price('总价:');
$price1 = new price(array('name' => '商品', 'price' => 100));
$price2 = new price(array('name' => '商品', 'price' => -2));
$total_prices->add($price1);
$total_prices->add($price2);
$total_prices->show();
}
}

$test = new test();
$test->run();
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐