PHP design pattern combination pattern belongs to structural pattern
Overview: Combine objects into a tree structure to represent the 'partial-uniyun' hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.
Both combination and aggregation describe the situation where a class holds one or more instances of other classes for a long time.
Aggregation: contained objects are the core part of the container, but they can also be contained by other objects. The aggregation relationship is illustrated by a line starting with a hollow diamond.
Combination: the contained object can only be referenced by its container. When the container is deleted, it should also be deleted. The Diamond of the composite relationship is solid.
/**
* Execution unit
*/
Abstract class Unit {
Public function bombardStrength ();
}
/**
* Archer
*/
Class ArcherUnit extends Unit {
Public function bombardStrength (){
Return 4;
}
}
/**
* Laser cannon
*/
Class LaserCannonUnit extends Unit {
Public function bombardStrength (){
Return 10;
}
}
/**
* Army
*/
Class Arm {
Private $ units = array ();
Private $ strength = 0;
Public function addUnit (Unit $ unit ){
Array_push ($ this-> units, $ unit );
}
Public function bombardStrength (){
Foreach ($ this-> units as $ unit ){
$ This-> strength + = $ unit-> bombardStrength ();
}
}
}
/**
* Combination mode
*/
Public function actionCombine (){
$ Archer = new ArcherUnit;
$ LaserCannon = new LaserCannonUnit;
$ Arm = new Arm;
$ Arm-> addUnit ($ archer );
$ Arm-> addUnit ($ laserCannon );
Echo $ arm-> bombardStrength ();
}