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

来源:互联网 发布:百万公众网络答题工程 编辑:程序博客网 时间:2024/04/27 07:00
组合模式:将一组对象组合为可像单个对像一样被使用的结构
<?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();?>

0 0
原创粉丝点击