PHP Object-Oriented Programming combination mode and decorative mode details, python object-oriented details
This article describes the PHP Object-Oriented Programming combination mode and decoration mode. We will share this with you for your reference. The details are as follows:
Combination Mode
Definition: A combination mode defines a single inheritance system that allows a set of distinct responsibilities to work side by side.
An army case,
<? Phpabstract class Unit {// individual abstract function bombardStrength ();} class Archer extends Unit {// Archer function bombardStrength () {return 4 ;}} class LaserCannonUnit extends Unit {// firejacker function bombardStrength () {return 44 ;}}?>
Integrate members of the army to output firepower
<? Phpabstract class Unit {abstract function bombardStrength ();} class Archer extends Unit {function bombardStrength () {return 4 ;}} class LaserCannonUnit extends Unit {function bombardStrength () {return 44 ;}} class Army {// military private $ units = array (); // defines the private attribute individual set function addUnit (Unit $ unit) {// Add member array_push ($ this-> units, $ unit);} function bombardStrength () {// firepower $ ret = 0; foreach ( $ This-> units as $ unit) {$ ret + = $ unit-> bombardStrength ();} return $ ret ;}$ unit1 = new Archer (); $ unit2 = new LaserCannonUnit (); $ army = new Army (); $ army-> addUnit ($ unit1); $ army-> addUnit ($ unit2 ); print $ army-> bombardStrength (); // output firepower?>
Output:
48
The army further integrates with other troops
<? Phpabstract class Unit {abstract function bombardStrength ();} class Archer extends Unit {function bombardStrength () {return 4 ;}} class LaserCannonUnit extends Unit {function bombardStrength () {return 44 ;}} class Army {private $ units = array (); private $ armies = array (); function addUnit (Unit $ unit) {array_push ($ this-> units, $ unit);} function addArmy (Army $ army) {array_push ($ this-> armi Es, $ army);} function bombardStrength () {$ ret = 0; foreach ($ this-> units as $ unit) {$ ret + = $ unit-> bombardStrength ();} foreach ($ this-> armies as $ army) {$ ret + = $ army-> bombardStrength ();} return $ ret; }}$ unit1 = new Archer (); $ unit2 = new LaserCannonUnit (); $ army = new Army (); $ army-> addUnit ($ unit1 ); $ army-> addUnit ($ unit2); print $ army-> bombardStrength (); print "\ n"; $ army2 = clone $ army ;// Clone an army $ army-> addArmy ($ army2); print $ army-> bombardStrength (); print "\ n";?>
Output:
48
96
It is better to support addition, removal, and other functions.
<? Phpabstract class Unit {abstract function addUnit (Unit $ unit); abstract function removeUnit (Unit $ unit); abstract function bombardStrength ();} class Army extends Unit {// military private $ units = array (); function addUnit (Unit $ unit) {if (in_array ($ unit, $ this-> units, true )) {// $ this is used to call a normal property or method. self calls a static method, property or constant return;} $ this-> units [] = $ unit ;} function removeUnit (Unit $ unit) {//> = Php 5.3 $ this-> units = array_udiff ($ this-> units, array ($ unit), function ($ a, $ B) {return ($ a ===$ B )? ;}); // <Php 5.3 // $ this-> units = array_udiff ($ this-> units, array ($ unit), // create_function ('$, $ B ', 'Return ($ a ===$ B )?; '); // Object array, create_function, CREATE function} function bombardStrength () {$ ret = 0; foreach ($ this-> units as $ unit) {$ ret + = $ unit-> bombardStrength ();} return $ ret ;}// quick example classesclass Tank extends Unit {// Tank function addUnit (Unit $ unit) {} function removeUnit (Unit $ unit) {} function bombardStrength () {return 4 ;}} class Soldier extends Unit {// Soldier function addUnit (Unit $ unit) {} Function removeUnit (Unit $ unit) {} function bombardStrength () {return 8 ;}}$ tank = new Tank (); $ tank2 = new Tank (); $ soldier = new Soldier (); $ army = new Army (); $ army-> addUnit ($ soldier); $ army-> addUnit ($ tank ); $ army-> addUnit ($ tank2); print_r ($ army); print $ army-> bombardStrength (). "\ n"; $ army-> removeUnit ($ soldier); print_r ($ army); print $ army-> bombardStrength (). "\ n";?>
Output:
Army Object( [units:Army:private] => Array ( [0] => Soldier Object ( ) [1] => Tank Object ( ) [2] => Tank Object ( ) ))16Army Object( [units:Army:private] => Array ( [1] => Tank Object ( ) [2] => Tank Object ( ) ))8
Add Exception Handling
<?phpabstract class Unit { abstract function addUnit( Unit $unit ); abstract function removeUnit( Unit $unit ); abstract function bombardStrength();}class Army extends Unit { private $units = array(); function addUnit( Unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { return; } $this->units[] = $unit; } function removeUnit( Unit $unit ) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff( $this->units, array( $unit ), create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); } function bombardStrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardStrength(); } return $ret; }}class UnitException extends Exception {}class Archer extends Unit { function addUnit( Unit $unit ) { throw new UnitException( get_class($this)." is a leaf" ); } function removeUnit( Unit $unit ) { throw new UnitException( get_class($this)." is a leaf" ); } function bombardStrength() { return 4; }}$archer = new Archer();$archer2 = new Archer();$archer->addUnit( $archer2 );?>
Output:
Fatal error: Uncaught exception 'unitexception' with message 'Archer is a leaf'
Comments: All classes in the combination mode share the same parent type. You can easily add new composite objects or partial objects in the design without modifying the code in a wide range.
The final effect is gradually optimized (perfect ):
<?phpclass UnitException extends Exception {}abstract class Unit { abstract function bombardStrength(); function addUnit( Unit $unit ) { throw new UnitException( get_class($this)." is a leaf" ); } function removeUnit( Unit $unit ) { throw new UnitException( get_class($this)." is a leaf" ); }}class Archer extends Unit { function bombardStrength() { return 4; }}class LaserCannonUnit extends Unit { function bombardStrength() { return 44; }}class Army extends Unit { private $units = array(); function addUnit( Unit $unit ) { if ( in_array( $unit, $this->units, true ) ) { return; } $this->units[] = $unit; } function removeUnit( Unit $unit ) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff( $this->units, array( $unit ), create_function( '$a,$b', 'return ($a === $b)?0:1;' ) ); } function bombardStrength() { $ret = 0; foreach( $this->units as $unit ) { $ret += $unit->bombardStrength(); } return $ret; }}// create an army$main_army = new Army();// add some units$main_army->addUnit( new Archer() );$main_army->addUnit( new LaserCannonUnit() );// create a new army$sub_army = new Army();// add some units$sub_army->addUnit( new Archer() );$sub_army->addUnit( new Archer() );$sub_army->addUnit( new Archer() );// add the second army to the first$main_army->addUnit( $sub_army );// all the calculations handled behind the scenesprint "attacking with strength: {$main_army->bombardStrength()}\n";?>
Output:
Attacking with strength: 60
More awesome combination processing,
<? Phpabstract class Unit {function getComposite () {return null;} abstract function bombardStrength ();} abstract class CompositeUnit extends Unit {// abstract class inherits the abstract class private $ units = array (); function getComposite () {return $ this;} protected function units () {return $ this-> units;} function removeUnit (Unit $ unit) {//> = php 5.3 // $ this-> units = array_udiff ($ this-> units, array ($ unit), // function ($ A, $ B) {return ($ a ===$ B )? ;}); // <Php 5.3 $ this-> units = array_udiff ($ this-> units, array ($ unit), create_function ('$ a, $ B ', 'Return ($ a ===$ B )?; ');} Function addUnit (Unit $ unit) {if (in_array ($ unit, $ this-> units, true) {return ;} $ this-> units [] = $ unit;} class Army extends CompositeUnit {function bombardStrength () {$ ret = 0; foreach ($ this-> units as $ unit) {$ ret + = $ unit-> bombardStrength ();} return $ ret;} class Archer extends Unit {function bombardStrength () {return 4 ;}} class LaserCannonUnit extends Unit {functi On bombardStrength () {return 44 ;}} class UnitScript {static function joinExisting (Unit $ newUnit, Unit $ occupyingUnit) {// static method, using the class name directly $ comp; if (! Is_null ($ comp = $ occupyingUnit-> getComposite () {// military merge processing $ comp-> addUnit ($ newUnit );} else {// soldier merge processing $ comp = new Army (); $ comp-> addUnit ($ occupyingUnit); $ comp-> addUnit ($ newUnit );} return $ comp ;}$ army1 = new Army (); $ army1-> addUnit (new Archer (); $ army1-> addUnit (new Archer ()); $ army2 = new Army (); $ army2-> addUnit (new Archer (); $ army2-> addUnit (new Archer (); $ army2-> addUnit (new LaserCannonUnit (); $ composite = UnitScript: joinExisting ($ army2, $ army1); print_r ($ composite);?>
Output:
Army Object( [units:CompositeUnit:private] => Array ( [0] => Archer Object ( ) [1] => Archer Object ( ) [2] => Army Object ( [units:CompositeUnit:private] => Array ( [0] => Archer Object ( ) [1] => Archer Object ( ) [2] => LaserCannonUnit Object ( ) ) ) ))
Comments: Basic Unit: add and remove are implemented in CompositeUnit combination. The army inherits Composite and the shooter inherits Archer. In this way, there will be no additional add and remove methods in the shooter.
Decoration Mode
The decoration mode helps us change the functions of specific components.
Look at the example
<? Phpabstract class Tile {// brick and Tile abstract function getWealthFactor (); // obtain wealth} class Plains extends Tile {// plain private $ wealthfactor = 2; function getWealthFactor () {return $ this-> wealthfactor;} class DiamondPlains extends Plains {// function getWealthFactor () {return parent: getWealthFactor () + 2 ;}} class PollutedPlains extends Plains {// function getWealthFactor () {return parent: g EtWealthFactor ()-4 ;}}$ tile = new PollutedPlains (); print $ tile-> getWealthFactor ();?>
Output:
-2
Comment: we are not flexible. We cannot get the funds for diamonds and contaminated land at the same time.
The decoration mode uses combination and delegation instead of inheritance to solve the problem of function changes.
Example:
<? Phpabstract class Tile {abstract function getWealthFactor ();} class Plains extends Tile {private $ wealthfactor = 2; function getWealthFactor () {return $ this-> wealthfactor ;}} abstract class TileDecorator extends Tile {// decoration protected $ tile; function _ construct (Tile $ tile) {$ this-> tile = $ tile ;}} class DiamondDecorator extends TileDecorator {// diamond decoration function getWealthFactor () {return $ this-> Tile-> getWealthFactor () + 2 ;}} class PollutionDecorator extends TileDecorator {// pollution decoration function getWealthFactor () {return $ this-> tile-> getWealthFactor () -4 ;}}$ tile = new Plains (); print $ tile-> getWealthFactor (); // 2 $ tile = new DiamondDecorator (new Plains ()); print $ tile-> getWealthFactor (); // 4 $ tile = new PollutionDecorator (new DiamondDecorator (new Plains (); print $ tile-> getWealthFactor ();// 0?>
Output:
2
4
0
Comment: This model is scalable. We do not need to create a DiamondPollutionPlains object to build a diamond contaminated object.
A more realistic example
<? Phpclass RequestHelper {} // request assistant abstract class ProcessRequest {// process request abstract function process (RequestHelper $ req );} class MainProcess extends ProcessRequest {// main process function process (RequestHelper $ req) {print _ CLASS __. ": doing something useful with request \ n" ;}} abstract class DecorateProcess extends ProcessRequest {// decoration process protected $ processrequest; function _ construct (ProcessRequest $ Pr) {// reference object, delegate $ this-> processrequest = $ pr;} class LogRequest extends DecorateProcess {// log request function process (RequestHelper $ req) {print _ CLASS __. ": logging request \ n"; // The current class. It is a bit recursive. $ this-> processrequest-> process ($ req );}} class AuthenticateRequest extends DecorateProcess {// authentication request function process (RequestHelper $ req) {print _ CLASS __. ": authenticating request \ n"; $ this-> processr Equest-> process ($ req);} class StructureRequest extends DecorateProcess {// organization structure request function process (RequestHelper $ req) {print _ CLASS __. ": structuring request \ n"; $ this-> processrequest-> process ($ req );}} $ process = new AuthenticateRequest (new StructureRequest (new LogRequest (new MainProcess (); // You can flexibly combine the relationship between processes, saves a lot of repeated inheritance $ process-> process (new RequestHelper (); print_r ($ process);?>
Output:
AuthenticateRequest: authenticating requestStructureRequest: structuring requestLogRequest: logging requestMainProcess: doing something useful with requestAuthenticateRequest Object( [processrequest:protected] => StructureRequest Object ( [processrequest:protected] => LogRequest Object ( [processrequest:protected] => MainProcess Object ( ) ) ))
Comment: There is a kind of recursive feeling, called layer by layer. The model is summed up by the cool people to flexibly solve some practical problems. Niu! Give development more ideas.