Current Location: Home> Latest Articles> Detailed Explanation of PHP Composite Pattern: A StarCraft Game Example

Detailed Explanation of PHP Composite Pattern: A StarCraft Game Example

gitbox 2025-07-22

Introduction

The Composite Pattern is a structural design pattern used to compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions uniformly, simplifying code structure significantly. This article uses the StarCraft game as an example to demonstrate the application of the Composite Pattern in detail.

Game Role Definitions

In the StarCraft game, common roles include Army, Soldier, and Tank. Below is the PHP code defining these roles and their behaviors.

abstract class Unit
{
    abstract public function attack();
}

class Soldier extends Unit
{
    public function attack()
    {
        echo "Soldier attacks!";
    }
}

class Tank extends Unit
{
    public function attack()
    {
        echo "Tank attacks!";
    }
}

class Army extends Unit
{
    private $units = [];

    public function addUnit(Unit $unit)
    {
        $this->units[] = $unit;
    }

    public function attack()
    {
        foreach ($this->units as $unit) {
            $unit->attack();
            echo "";
        }
    }
}

Composite Pattern Application Example

The Army is the composite object, while Soldiers and Tanks are leaf objects. The Army can contain multiple Soldiers and Tanks, and issue attack commands to all members uniformly.

$army = new Army();
$army->addUnit(new Soldier());
$army->addUnit(new Soldier());
$army->addUnit(new Tank());

By calling the Army's attack method, all members are commanded to attack at once:

$army->attack();

The output will be:

Soldier attacks!
Soldier attacks!
Tank attacks!

This demonstrates how the Composite Pattern enables unified management of complex object structures, greatly enhancing code flexibility and maintainability.

Summary

The Composite Pattern builds tree-structured object hierarchies, simplifying the treatment of individual and composite objects. In the StarCraft example, we successfully implemented unified control of an army and its members. Using the Composite Pattern makes the code cleaner and provides good scalability for complex system designs.

References