PHP design mode-policy Mode
Disclaimer: Cheng Jie, author of this series of blog references "big talk design mode.
Policy patterns define a series of algorithms, encapsulate each algorithm, and make them replaceable. The policy mode allows algorithms to change independently of customers who use them, that is, encapsulate the changed algorithms.
Applicable scenarios:
1. Multiple classes only differ in performance behavior. You can use the Strategy Mode to dynamically select the behavior to be executed during running.
2. Different policies (algorithms) need to be used in different situations, or they may be implemented in other ways in the future.
3. Hiding implementation details of specific policies (algorithms) from customers is completely independent of each other.
4. The client must know all the policy classes and decide which policy classes to use. The policy mode is only applicable when the client knows all the algorithms or actions.
5. The policy mode creates many policy classes. Each specific policy class produces a new class.
Sometimes you can save the environment-dependent status to the client, and you can use the enjoy mode to reduce the number of objects.
UML class diagram:
Role analysis:
Abstract policy role (RotateItem): A Policy class, usually implemented by an interface or abstract class.
Specific policy role (ItemX): encapsulates related algorithms and behaviors.
Environment role (ItemContext): holds a reference to the policy class and calls it to the client.
Code implementation:
;} Function unInertisRotate () {echo I am an X product, and I am not rotating inertia .; }/** Specific policy role -- Y product * Class YItem */class YItem implements RotateItem {function inertiaRotate () {echo I am a Y product, and I cannot rotate inertia .; } Function unInertisRotate () {echo: I am a Y product, and I am not rotating inertia .; }/** Specific policy role -- XY product * Class XYItem */class XYItem implements RotateItem {function inertiaRotate () {echo I am a XY product, and I rotate in inertia .; } Function unInertisRotate () {echo I am a XY product, and I am rotating non-inertial .; } Class contextStrategy {private $ item; function getItem ($ item_name) {try {$ class = new ReflectionClass ($ item_name ); $ this-> item = $ class-> newInstance ();} catch (ReflectionException $ e) {$ this-> item = ;}} function inertiaRotate () {$ this-> item-> inertiaRotate ();} function unInertisRotate () {$ this-> item-> unInertisRotate ();}}
Client call code: