Policy Mode, encapsulating a specific set of behaviors and algorithms into classes to accommodate certain contexts, a pattern that
Policy Mode,
Policy ModeFor the free switching and expansion of the algorithm, it is widely used
Design PatternsOne.
<?php/* * Policy mode */interface flybehavior{public function Fly (); Class Flywithwings implements flybehavior{public function Fly () { echo "duck flies with wings \ n"; }} Class Flywithno implements flybehavior{public function Fly () { echo "duck flies without wings \"; }} Class duck{ private $_flybehavior; Public Function Performfly () { $this->_flybehavior->fly (); } Public Function Setflybehavior (Flybehavior $behavior)//external call to set policy { $this->_flybehavior = $behavior; } }class Rubberduck extends duck{}//Test case$duck = new Rubberduck (); /* Want the Ducks to fly with their wings */$duck->setflybehavior (new Flywithwings ()); $duck->performfly ();/* want the Ducks to fly without wings */$duck->setflybehavior (New Flywithno ()); $duck Performfly ();
The policy mode is used for the free switching and expansion of the algorithm, which is one of the most widely used design patterns. The policy pattern corresponds to an algorithm family that solves a problem, allows the user to choose an algorithm from the algorithm family to solve a problem, and can easily replace the algorithm or add a new algorithm. You can consider using policy mode as long as the encapsulation, multiplexing, and switching of the algorithms are involved.
Related recommendations:
PHP policy pattern definition and usage examples
Code Sharing for PHP policy mode
The PHP strategy mode of StarCraft