PHP design pattern-decorator pattern

Source: Internet
Author: User
Tags zend framework
The modifier mode dynamically attaches the responsibility to the object. If you want to expand functions, the decorator provides an alternative solution that is more flexible than inheritance.
The modifier mode dynamically attaches the responsibility to the object. To expand the functionality, the decorator provides an alternative solution that is more flexible than inheritance.

Mind Map

There is such a project as a restaurant ordering system. The initial code structure is as follows. There are many inheritance classes for Beverage. The problem is that the price of Milk has increased, so we need to adjust all the related classes, such as the Milk and SugarAndMilk classes, there are many other types of methods. we need to modify the methods in the class one by one. every time developers do this, it's crazy! So we need to change the existing structure. The following figures are all simple. the actual figure is not that simple.

Design issues:

1. the number of categories has exploded and many categories are difficult to maintain;
2. rigid design;
3. new features added to the base class cannot be used in child classes;
There are many ways to reuse class methods, such as inheritance, combination, and delegation. Why do we always get used to inheritance? I think Zend Framework also has this habit! Find the corresponding method each time and continue to flip it up. -- Digress !!!!
After a group study, we decided to extract the basic category. for example, we made coffee into a separate category. other coffee, such as milk coffee and sweet coffee, we only pack the materials into one class separately.
Improved design:

Details
1. for drinks, we directly inherit the Beverage class and directly write the quotation into the Beverage category;
2. for some special drinks that require condiments, we will accumulate them. For example, if I want a cup of coffee, the total price = coffee price + milk price
3. it is easy to know the price of different drinks.
Code
The code is as follows:
Abstract class Beverage {
Public $ _ name;
Abstract public function Cost ();
}
// Decorator class
Class Coffee extends Beverage {
Public function _ construct (){
$ This-> _ name = 'coffee ';
}
Public function Cost (){
Return 1.00;
}
}
// The following three classes are related to the modifier
Class CondimentDecorator extends Beverage {
Public function _ construct (){
$ This-> _ name = 'condition ';
}
Public function Cost (){
Return 0.1;
}
}
Class Milk extends CondimentDecorator {
Public $ _ beverage;
Public function _ construct ($ beverage ){
$ This-> _ name = 'milk ';
If ($ beverage instanceof Beverage ){
$ This-> _ beverage = $ beverage;
} Else
Exit ('failed ');
}
Public function Cost (){
Return $ this-& gt; _ beverage & gt; Cost () + 0.2;
}
}
Class Sugar extends CondimentDecorator {
Public $ _ beverage;
Public function _ construct ($ beverage ){
$ This-> _ name = 'hangzhou ';
If ($ beverage instanceof Beverage ){
$ This-> _ beverage = $ beverage;
} Else {
Exit ('failed ');
}
}
Public function Cost (){
Return $ this-& gt; _ beverage & gt; Cost () + 0.2;
}
}
// Test Case
// 1. get a cup of coffee
$ Coffee = new Coffee ();
// 2. add some milk
$ Coffee = new Milk ($ coffee );
// 3. add some sugar
$ Coffee = new Sugar ($ coffee );
Printf ("Coffee Total: % 0.2f RMB \ n", $ coffee-> Cost ());

Summary
1. the decorator (Milk) and the decorator (Coffee) must be of the same type. The purpose is that the decorator must replace the decorator.
2. add behavior: When the decorator and component are combined, a new behavior is added.
Digress:
1. using inheritance to design subclass behavior is determined statically during compilation, and all subclasses will inherit the same behavior. For example, I want to learn some kung fu. I think your kiddies will do Taijiquan. I only need to inherit from you, and I will do it.-haha, then I will become your son, it seems that inheritance has to pay a price.
2. combination, we can expand the behavior of the object and dynamically expand it at runtime. With the combination, we can add methods that we didn't think of when designing the superclass to the object at any time without changing the existing code. For example, Lao Tzu does not have an internal force, and he absorbs the internal force (behavior object) of monks, nangu, and Taoist, which is in the fight (runtime, I can use different internal forces at any time, but I can't suck the internal forces randomly. Otherwise, you will be defeated!
3. classes should be open to extensions and closed to modifications. If each part is designed in the modifier mode, it is a waste for the entire framework, and you also increase the difficulty of code. When will this mode be used? We are generally used for frequent changes. So how do we know what is often changed? This requires our experience and your understanding of the industry. We recommend that you read more examples.
4. the decoration mode injects elasticity into the design, but a large number of small classes are added to the design, which occasionally makes it difficult for others to understand the design.
5. when using the decorator mode, be especially careful when inserting the decorator. Because the decorator mode depends on a specific type (Beverage ).
6. to use the decorator mode well, we also need to use the factory mode and generator mode, but today we only talk about the decorator mode. To learn more, let's look at the next decomposition.
References: head first design model

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.