组合模式设计购物车价格计算实例(仅供学习使用)
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(); ?>
相关文章推荐
- 设计模式实例学习-单例模式(Android中的使用场景)
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)
- [学习笔记]jsp+javaBean+Servlet 的设计模式MVC 的实例
- 设计模式学习(七)----迭代和组合
- Net设计模式实例之组合模式(Composite Pattern)(3)
- C# 设计模式学习三 Abstract Factory 抽象工厂(实例)
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(3)
- 设计模式学习笔记十七:组合模式(Composite Pattern)
- 2009 年8 月6号 学习 uml、ea、设计模式以及如何使用它们进行分析、设计
- 设计模式----优先使用对象组合,而非类继承
- Net设计模式实例之组合模式(Composite Pattern)(2)
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(3)
- (Head First 设计模式)学习笔记(2) --观察者模式(气象站实例)
- 设计模式学习1—使用单件模式解决对象重复申请问题
- 敏捷思维-架构设计中的方法学(7)组合使用模式
- JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)
- (Head First 设计模式)学习笔记(3) --装饰者模式(StarBuzz咖啡店实例)
- (Head First 设计模式)学习笔记(3) --装饰者模式(StarBuzz咖啡店实例)
- Net设计模式实例之组合模式(Composite Pattern)
- C#面向对象设计模式学习笔记(8) - Composite 组合模式(结构型模式)