<?php
//装饰模式
abstract class Food
{
abstract public function getDes();
abstract public function getCost();
}
//一个具体类
class Rice extends Food
{
private $des = '饭';
private $cost = 0.50;
public function getDes()
{
return $this->des;
}
public function getCost()
{
return $this->cost;
}
}
//装饰类
class Vegetables extends Food
{
public $obj;
public function __construct( Food $obj )
{
$this->obj=$obj;
}
public function getDes()
{
$this->obj->getDes();
}
public function getCost()
{
$this->obj->getCost();
}
}
//修饰类:土豆丝
class Potato extends Vegetables
{
var $des= '土豆丝';
var $cost= 6.00;
public function getDes()
{
return $this->des.$this->obj->getDes();
}
public function getCost()
{
return $this->obj->getCost() + $this->cost;
}
}
//修饰类:西红柿
class Tomato extends Vegetables
{
var $des= '西红柿';
var $cost= 5.00;
public function getDes()
{
return $this->des.$this->obj->getDes();
}
public function getCost()
{
return $this->obj->getCost() + $this->cost;
}
}
//修饰类:咸菜
class Pickle extends Vegetables
{
var $des= '咸菜';
var $cost= 3.50;
public function getDes()
{
return $this->des.$this->obj->getDes();
}
public function getCost()
{
return $this->obj->getCost() + $this->cost;
}
}
//工厂类
class FoodFactory
{
const VEGETABLES_TYPE_POTATO = 1;
const VEGETABLES_TYPE_TOMATO = 2;
const VEGETABLES_TYPE_PICKLE = 3;
var $parm = array();
var $obj = null;
public function __construct( $items )
{
$this->parm = $items;
}
public function getResult()
{
$this->obj = new Rice();
if( $this->parm )
{
foreach ( $this->parm as $item )
{
switch ( $item )
{
//土豆丝
case self::VEGETABLES_TYPE_POTATO:
$this->obj = new Potato( $this->obj );
break;
//西红柿
case self::VEGETABLES_TYPE_TOMATO:
$this->obj = new Tomato( $this->obj );
break;
//咸菜
case self::VEGETABLES_TYPE_PICKLE:
$this->obj = new Pickle( $this->obj );
break;
}
}
}
return $this->obj->getDes().":".$this->obj->getCost();
}
}
//在这里使用
//数组里面可以是1,2,3中的任意元素
//$vegetables = array();
//$vegetables = array( 1 , 2, 3 );
$vegetables = array( 1 , 2 ,3 );
//$vegetables = array( 1 , 3 );
$lunch = new FoodFactory( $vegetables );
echo $lunch->getResult();
?>