PHP design pattern combination pattern

Source: Internet
Author: User
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 ();

}

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.