The decorative mode of PHP design pattern

Source: Internet
Author: User

Here is a simple class to help understand the decorative pattern, hope to be helpful to everyone, some places to change to Chinese, easy to understand.

I have to eat at a restaurant, and the result of the program is to print a description of what I eat and to calculate the price.

Such a layer of bag down, such as large pockets, small pockets, is the so-called decorative mode.

Base class
Class Food {
var $des = ' food ';
var $cost;
function Getdes () {
return $this->des;
}
function Getcost () {
return $this->cost;
}
}
Decorated Person class
Class Rice extends Food {
var $des = "Rice";
var $cost = 0.44;
}
The adorner class inherits from the same base class as the decorated person
Class Dish extends Food {
var $obj;
var $des = ';
var $cost;
}
A subdivision of a decorated person
Class fried potato silk extends dish {
var $obj;
var $des = ' potato silk ';
var $cost = 0.10;
function __construct ($obj) {
$this->obj= $obj;
}
function Getdes () {
return $this->obj->getdes (). $this->des;
}
function Getcost () {
return $this->obj->getcost () + $this->cost;
}
}
There is a subdivision of the decorator who
Class Pickles extends Vegetables {
var $obj;
var $des = ' Pickles ';
var $cost = 0.10;
function __construct ($obj) {
$this->obj= $obj;
}
function Getdes () {
return $this->obj->getdes (). $this->des;
}
function Getcost () {
return $this->obj->getcost () + $this->cost;
}
}
More dishes
......
Test code
$ lunch = new Rice ();
$ Lunch =new Potato thread ($ lunch);
$ Lunch =new Pickles ($ lunch);
echo $ lunch->getdes ();//outputs rice, potato shreds, pickles.
echo $ lunch->getcost ();//outputs 0.64

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.